码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2018-02-10 15:02:57      阅读:170      评论:0      收藏:0      [点我收藏+]

标签:public   tac   get   ext   enc   tty   setfile   address   from   

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发送邮件(纯文本和带附件)

标签:public   tac   get   ext   enc   tty   setfile   address   from   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!