public class TestMail {
//纯文本
@Test
public void fun()throws AddressException,MessagingException{
Properties prop=new Properties();
prop.setProperty("mail.host", "smtp.163.com");
prop.setProperty("mail.smtp.auth", "true");
Authenticator auth=new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication("发件人的邮箱","发件人的密码" );
}
};
Session session=Session.getInstance(prop,auth);
MimeMessage msg=new MimeMessage(session);
msg.setFrom(new InternetAddress("发件人的邮箱"));
msg.setRecipients(RecipientType.TO, "收件人的邮箱");
msg.setSubject("啦啦啦!!!");//标题
msg.setContent("啦啦啦!", "text/html;charset=utf-8"); //内容
Transport.send(msg);
}
//带附件的
@Test
public void fun2()throws AddressException,MessagingException,IOException{
Properties prop=new Properties();
prop.setProperty("mail.host", "smtp.163.com");
prop.setProperty("mail.smtp.auth", "true");
Authenticator auth=new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication("发件人的邮箱","发件人的密码" );
}
};
Session session = Session.getInstance(prop, auth);
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress("发件人的邮箱"));
msg.setRecipients(RecipientType.TO,"收件人的邮箱");
msg.setSubject("测试邮件"); //标题
MimeMultipart list = new MimeMultipart();
MimeBodyPart part1 = new MimeBodyPart();
part1.setContent("啦啦啦!", "text/html;charset=utf-8"); //内容
list.addBodyPart(part1);
MimeBodyPart part2 = new MimeBodyPart();
part2.attachFile("D:\\title_en.png"); //附件
part2.setFileName(MimeUtility.encodeText("title_en.png"));
list.addBodyPart(part2);
msg.setContent(list);
Transport.send(msg);
}
}
原文地址:https://www.cnblogs.com/leixia/p/8438590.html