乐趣区

关于java:java实现邮件发送

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

1、配置依赖包

<dependency>

        <groupId>javax.mail</groupId>
        <artifactId>mail</artifactId>
        <version>1.5.0-b01</version>
    </dependency>

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

留神受权码保留好!!!

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 = "xxx@163.com";
    // 受权码
    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 = "1819436405@qq.com";
    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());
}

}

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

退出移动版