首页 > 编程语言 > 详细

java发送邮件(纯文本和带附件)

时间:2018-02-10 14:37:28      阅读:213      评论:0      收藏:0      [点我收藏+]

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);
}
}

java发送邮件(纯文本和带附件)

原文:https://www.cnblogs.com/leixia/p/8438590.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!