java 发送邮件

创建时间:2022-08-25 16:09:43
栏目:java

java发送邮件代码

package com.sdp.mailtest;
import javax.mail.*;
import javax.mail.event.TransportEvent;
import javax.mail.event.TransportListener;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Date;
import java.util.Properties;

public class MailTest {
    public static void main(String[] args) throws Exception{
        //1.创建参数配置,用于连接邮件服务器的参数配置

        Properties properties=new Properties();

        properties.setProperty("mail.transport.protocol", "smtps");//使用的协议(JavaMail规范要求)

        properties.setProperty("mail.smtps.host", "smtp.ym.163.com");//发件人的邮箱的 SMTP 服务器地址

        properties.setProperty("mail.smtps.auth", "true");//需要请求认证

        properties.setProperty("mail.smtps.port", "994");

    // 非ssl请用下面的代码

        //properties.setProperty("mail.transport.protocol", "smtp");//使用的协议(JavaMail规范要求)

        //properties.setProperty("mail.smtp.host", "smtp.ym.163.com");//发件人的邮箱的 SMTP 服务器地址

        //properties.setProperty("mail.smtp.auth", "true");//需要请求认证

        //properties.setProperty("mail.smtp.port", "25");



        // 2. 根据配置创建会话对象, 用于和邮件服务器交互

        Session session=Session.getInstance(properties);

        session.setDebug(true);//设置为debug模式,可以查看详细的发送log

        //3.创建一封邮件

        MimeMessage message= createMimeMessage(session, "send@shushi3.com", "tomail@qq.com");

//4.根据session获取邮件传输对象

        Transport transport=session.getTransport();

        transport.connect("noReply@shushi3.com", "你的邮箱密码");

        transport.sendMessage(message,message.getAllRecipients());

        transport.close();//关闭连接

        System.out.println("邮件发送成功");
    }
    private static MimeMessage createMimeMessage(Session session, String sendMail, String receiveMail)throws Exception {

        // TODO Auto-generated method stub

        MimeMessage message=new MimeMessage(session);//创建一封邮件

        message.setFrom(new InternetAddress(sendMail, "邮件", "UTF-8"));//发件人

        message.setRecipient(MimeMessage.RecipientType.TO,new InternetAddress(receiveMail, "Mary", "UTF-8"));//收件人

        message.setSubject("解释","UTF-8");//邮件主题

        message.setContent("这是用程序发送的邮件哦,不是在客户端上写的", "text/html;charset=utf-8");

        message.setSentDate(new Date());

        message.saveChanges();//保存设置

        return message;

    }
}

联系我们

微信号:shidaping023