Java邮件发送(JavaMail)

1. JavaMail简介

​ JavaMail 是sun公司(现以被甲骨文收购)为方便Java开发人员在应用程序中实现邮件发送和接收功能而提供的一套标准开发包,它支持一些常用的邮件协议如SMTP,POP3,IMAP等。使用JavaMail API 编写邮件时,无须考虑邮件的底层实现细节,只要调用JavaMail 开发包中相应的API即可

  

2. maven依赖

<dependency>
    <groupId>javax.mail</groupId>
    <artifactId>mail</artifactId>
    <version>1.4.7</version>
</dependency>

 
 
  

3. 发送邮件

/**
 * 发送邮件
 * SMTP协议   邮件代发协议
 * POP3协议   邮件代收协议
 */
public class MyMail {
    public static void main(String[] args) throws Exception {
            sendMsg();
    }

    public static void sendMsg() throws Exception {
        Properties props = new Properties();
        //设置代发协议  smtp
        props.setProperty("mail.transport.protocol", "smtp");
        //设置新浪的smtp代发服务器
        props.setProperty("mail.smtp.host", "smtp.163.com");
        //设置端口
        props.setProperty("mail.smtp.port", "25");
        //创建会话
        Session session = Session.getInstance(props);
        //打开调试模式就有发送邮件的详细信息了
        session.setDebug(true);

        //创建消息对象
        Message msg = new MimeMessage(session);
        //设置发送邮件的源地址
        msg.setFrom(new InternetAddress("[email protected]"));
        //设置发送邮件的目的地
        msg.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress("[email protected]"));
        //设置邮件主题
        msg.setSubject("happy new year");
        //设置邮件内容
        msg.setContent("xxx,新年快乐", "text/html;charset=utf-8");

        //获取邮件的传输对象
        Transport transport = session.getTransport();
        //用户名:邮箱地址    密码:smtp的授权码(千万千万不要在这写密码)
        transport.connect("[email protected]", "授权码");
        transport.sendMessage(msg, msg.getAllRecipients());
        transport.close();
    }
}

猜你喜欢

转载自blog.51cto.com/13062751/2376330