首页 > 编程语言 >Java实现邮件发送

Java实现邮件发送

时间:2022-10-26 18:46:34浏览次数:60  
标签:Java prop 发送 session new mail message 邮件

这里我们以QQ邮箱为例。

一、导入依赖:

    <dependencies>
        <!-- https://mvnrepository.com/artifact/javax.activation/activation -->
        <dependency>
            <groupId>javax.activation</groupId>
            <artifactId>activation</artifactId>
            <version>1.1.1</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/javax.mail/mail -->
        <dependency>
            <groupId>javax.mail</groupId>
            <artifactId>mail</artifactId>
            <version>1.4.7</version>
        </dependency>
    </dependencies>

二、设置自己的QQ邮箱

 

 开启以上两项服务。

三、具体实现

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 SendEmail {

    /* addressee:收件人邮箱
     *title:邮件标题标题
     *content:邮件内容
     */
    public static void send(String addressee, String title, String content) throws Exception {

        Properties prop = new Properties();
        prop.setProperty("mail.host", "smtp.qq.com");//邮件服务器:QQ
        prop.setProperty("mail.transport.protocol", "smtp");//邮件发送协议:smtp
        prop.setProperty("mail.smtp.auth", "true");//需要验证用户名和密码

        //QQ邮箱,还需要设置SSL加密
        MailSSLSocketFactory factory = new MailSSLSocketFactory();
        factory.setTrustAllHosts(true);
        prop.put("maim.smtp.ssl.enable", "true");
        prop.put("maim.smtp.ssl.socketFactory", factory);

        //javaMail发送email的五个步骤
        //1.定义一个整个应用环境需要的session对象
        Session session = Session.getDefaultInstance(prop, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("自己的邮箱", "授权码");
            }
        });
        //开启session的debug模式
        session.setDebug(true);
        //2.通过session得到transport对象
        Transport transport = session.getTransport();
        //3.使用邮箱用户名和授权码连接上服务器
        transport.connect("smtp.qq.com", "自己的邮箱", 授权码");
        //4.创建邮件
        //创建邮件对象
        MimeMessage message = new MimeMessage(session);
        //发邮件人
        message.setFrom(new InternetAddress("自己的邮箱"));
        //收件人 可以群发setRecipients
        message.setRecipient(Message.RecipientType.TO, new InternetAddress(addressee));
        //邮件标题
        message.setSubject(title);
        //邮件内容,前内容,后格式
        message.setContent(content, "text/html;charset=UTF-8");
        //5.发送邮件
        transport.sendMessage(message, message.getAllRecipients());
        //6.关闭连接
        transport.close();
    }
}

 

 

(本文仅作个人学习记录用,如有纰漏敬请指正)

标签:Java,prop,发送,session,new,mail,message,邮件
From: https://www.cnblogs.com/jmsstudy/p/16829592.html

相关文章