Java如何实现简单邮件发送功能

发布时间:2022-06-22 13:37:03 作者:iii
来源:亿速云 阅读:203

本篇内容介绍了“Java如何实现简单邮件发送功能”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

需要的jar包:

QQ邮箱设置开启POP3/SMTP服务,并获得授权码

java实现简单邮件发送

import com.sun.mail.util.MailSSLSocketFactory;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

public class Mail1 {
    public static  void main(String[] args) throws Exception {
        //要发送邮件,需要获得协议和支持!开启服务POP3/SMTP服务  授权码: fsxqgovorymigfeb
        Properties prop=new Properties();
        prop.setProperty("mail.host","smtp.qq.com");//设置QQ邮件服务器
        prop.setProperty("mail.transport.protocol","smtp");//设置邮箱发送协议
        prop.setProperty("mail.smtp.auth","true");//需要验证用户名密码

        //QQ邮箱还有设置SSL加密
        MailSSLSocketFactory sf=new MailSSLSocketFactory();
        sf.setTrustAllHosts(true);
        prop.put("mail.smtp.ssl.enable","true");
        prop.put("mail.smtp.ssl.socketFactory",sf);

        //1.创建定义整个应用程序所需要的环境信息的Session对象
        Session session=Session.getDefaultInstance(prop, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("1369410772@qq.com","fsxqgovorymigfeb");
            }
        });

        //开启session的debug模式,这样就可以查看运行状态了
        session.setDebug(true);

        //2.通过session对象获得transport对象
        Transport transport = session.getTransport();

        //3.使用邮箱的用户名和授权码连上邮件服务器
        transport.connect("smtp.qq.com","1369410772@qq.com","fsxqgovorymigfeb");
        //4.创建邮件:写邮件
        MimeMessage message = new MimeMessage(session);

        message.setFrom(new InternetAddress("1369410772@qq.com"));//发件人
        message.setRecipient(Message.RecipientType.TO,new InternetAddress("1369410772@qq.com"));//收件人
        message.setSubject("你好");//邮件主题
        message.setContent("<h2 style='color: red'>你好</h2>","text/html;charset=utf-8");//邮件内容
        //5.发送邮件
        transport.sendMessage(message,message.getAllRecipients());
        //6.关闭连接
        transport.close();

    }
}

java实现复杂邮件发送( 带文件 )

import com.sun.mail.util.MailSSLSocketFactory;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.util.Properties;

public class Mail1 {
    public static  void main(String[] args) throws Exception {
        //要发送邮件,需要获得协议和支持!开启服务POP3/SMTP服务  授权码: fsxqgovorymigfeb
        Properties prop=new Properties();
        prop.setProperty("mail.host","smtp.qq.com");//设置QQ邮件服务器
        prop.setProperty("mail.transport.protocol","smtp");//设置邮箱发送协议
        prop.setProperty("mail.smtp.auth","true");//需要验证用户名密码

        //QQ邮箱还有设置SSL加密
        MailSSLSocketFactory sf=new MailSSLSocketFactory();
        sf.setTrustAllHosts(true);
        prop.put("mail.smtp.ssl.enable","true");
        prop.put("mail.smtp.ssl.socketFactory",sf);

        //1.创建定义整个应用程序所需要的环境信息的Session对象
        Session session=Session.getDefaultInstance(prop, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("1369410772@qq.com","fsxqgovorymigfeb");
            }
        });

        //开启session的debug模式,这样就可以查看运行状态了
        session.setDebug(true);

        //2.通过session对象获得transport对象
        Transport transport = session.getTransport();

        //3.使用邮箱的用户名和授权码连上邮件服务器
        transport.connect("smtp.qq.com","1369410772@qq.com","fsxqgovorymigfeb");
        //4.创建邮件:写邮件
        MimeMessage message = new MimeMessage(session);

        message.setFrom(new InternetAddress("1369410772@qq.com"));//发件人
        message.setRecipient(Message.RecipientType.TO,new InternetAddress("1369410772@qq.com"));//收件人
        message.setSubject("你好");//邮件主题
        //message.setContent("<h2 style='color: red'>你好</h2>","text/html;charset=utf-8");//邮件内容

        //=============================================================================
        //带图片的内容
        MimeBodyPart image = new MimeBodyPart();
        DataHandler dh = new DataHandler(new FileDataSource("E:\\IDEA\\JavaWeb\\mail-java\\src\\tx.png"));//图片需要经过数据处理... DataHandler:数据处理
        image.setDataHandler(dh);//在Body中放入处理的图片数据
        image.setContentID("tx.png");//给图片设置ID

        //准备正文数据
        MimeBodyPart text = new MimeBodyPart();
        text.setContent("这是一封邮件正文带图片<img src='cid:tx.png'>的邮件","text/html;charset=utf-8");

        //描述数据关系
        MimeMultipart mm = new MimeMultipart();
        mm.addBodyPart(text);
        mm.addBodyPart(image);
        mm.setSubType("mixed");

        //设置到消息中,保存修改
        message.setContent(mm);
        message.saveChanges();
        //=========================================================================

        //5.发送邮件
        transport.sendMessage(message,message.getAllRecipients());
        //6.关闭连接
        transport.close();

    }
}

Spring实现

1、添加依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
</dependency>

2、编写配置文件

spring.mail.username=1369410772@qq.com
spring.mail.password=fsxqgovorymigfeb
spring.mail.host=smtp.qq.com
spring.mail.properties.mail.smtp.ssl.enable=true

3、编写测试类

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;

@SpringBootTest
class DemoApplicationTests {//简单邮件

    @Autowired
    JavaMailSenderImpl mailSender;

    @Test
    void contextLoads() {
        //发送邮件
        //收件人
        //内容

        SimpleMailMessage message = new SimpleMailMessage();
        message.setSubject("测试");
        message.setText("Hello");
        message.setFrom("1369410772@qq.com");
        message.setTo("1369410772@qq.com");
        mailSender.send(message);

    }

    @Test
    public void test2() throws Exception {//复杂邮件
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
        helper.setSubject("测试");
        helper.setText("Hello",true);

        //附件
        helper.addAttachment("1.jpg",new File(""));

        helper.setFrom("1369410772@qq.com");
        helper.setTo("1369410772@qq.com");

        mailSender.send(mimeMessage);

    }

}

“Java如何实现简单邮件发送功能”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注亿速云网站,小编将为大家输出更多高质量的实用文章!

推荐阅读:
  1. 使用Python怎么实现邮件发送功能
  2. Java如何实现简单密码加密功能

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

java

上一篇:TypeScript中的类型断言语法怎么使用

下一篇:Java中JDBC如何使用

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》