java实现邮件发送

java实现邮件自动网易邮箱发送

1、配置依赖包

        javax.mail
        mail
        1.5.0-b01
    

2、需要到网易邮箱开始服务

注意授权码保存好!!!
java实现邮件发送_第1张图片

3、代码

public class ClientEmail {

public static void main(String[] args) throws Exception {
    Properties props = new Properties();
    //设置邮件地址
    props.put("mail.host", "smtp.163.com");
    props.put("mail.transport.protocol", "smtp");
    //开启认证
    props.put("mail.smtp.auth", "true");
    Session session = Session.getDefaultInstance(props, null);
    Transport transport = session.getTransport();
    //用户名
    String user = "[email protected]";
    //授权码
    String password = "****************";      
    transport.connect(user, password);
    //创建邮件消息
    MimeMessage msg = new MimeMessage(session);
    msg.setSentDate(new Date());
    //邮件发送人
    InternetAddress fromAddress = new InternetAddress(user, "邮件服务");
    msg.setFrom(fromAddress);
    //邮件接收人
    String to = "[email protected]";
    InternetAddress[] toAddress = new InternetAddress[]{new InternetAddress(to)};
    msg.setRecipients(Message.RecipientType.TO, toAddress);
    //邮件主题
    msg.setSubject("测试邮件发送", "UTF-8");
    //内容和附件
    Multipart multipart = new MimeMultipart();
    //内容
    BodyPart contentBodyPart = new MimeBodyPart();
    contentBodyPart.setContent("test00001", "text/html;charset=UTF-8");
    multipart.addBodyPart(contentBodyPart);
    //附件
    BodyPart fileBody = new MimeBodyPart();
    DataSource source = new FileDataSource("C:/图片");
    fileBody.setDataHandler(new DataHandler(source));
    fileBody.setFileName("0b8da2cf424d1.jpg");
    multipart.addBodyPart(fileBody);
    //邮件内容
    msg.setContent(multipart);
    msg.saveChanges();
    //发送
    transport.sendMessage(msg, msg.getAllRecipients());
}

}

注意要配置好参数,不然会发送有问题。

你可能感兴趣的:(javaspring后端)