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

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);
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值