使用JavaMail通过SMTP协议发送纯文本邮件

public class JavaMailDemo {
    public static void main(String[] args) throws Exception {
        Properties props = new Properties();
        //使用协议:smtp,切记不要使用大写
        props.setProperty("mail.transport.protocol", "smtp");
        //smtp协议地址,这里已QQ邮箱为例
        props.setProperty("mail.smtp.host", "smtp.qq.com");
        //协议端口,这里已QQ邮箱为例
        props.setProperty("mail.smtp.port", "465"); 
        //需要授权,这里已QQ邮箱为例
        props.setProperty("mail.smtp.auth", "true");    
        //QQ邮箱SSL安全认证,其他邮箱不一定都需要进行SSL安全认证,
        props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");   
        //该程序只处理SSL安全认证的邮箱
        props.setProperty("mail.smtp.socketFactory.fallback", "false"); 
        //这里配置smtp端口
        props.setProperty("mail.smtp.socketFactory.port", "465");   
        //将smtp相关配置存储到session对象
        Session session = Session.getInstance(props);
        //开启日志
        session.setDebug(true);
        //创建邮件
        MimeMessage mimeMessage = createMimeMessage(session,"[email protected]","[email protected]");
        //建立连接对象
        Transport transport = session.getTransport();
        //建立连接,密码可以使用授权码
        transport.connect("[email protected]","nvvuidhaojdpbeca");
        transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
        //关闭连接
        transport.close();
    }
    
    //MimeMessage:邮件
    public static MimeMessage createMimeMessage(Session session,String sender,String recipient) throws Exception {
                //MimeMessage用于配置置邮件的发件人、收件人、标题、正文等内容
        MimeMessage message = new MimeMessage(session);
                //配置发件人
        Address address =new InternetAddress(sender, "白石紬", "UTF-8");
        //将发件人的Address对象存储到MimeMessage对象 
        message.setFrom(address);
        message.setSubject("此处为标题内容","utf-8");
        message.setContent("此处为正文内容", "text/html;charset=utf-8");
        //配置收件人:RecipientType.TO普通收件人、RecipientType.CC抄送、RecipientType.BCC密送
        message.setRecipient(MimeMessage.RecipientType.TO,new InternetAddress(recipient,"收件人A","UTF-8"));
        //发送时间
        message.setSentDate(new Date());
        //保存邮件
        message.saveChanges();
        return message;
    }
}

你可能感兴趣的:(使用JavaMail通过SMTP协议发送纯文本邮件)