標籤: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發送郵件(純文字和帶附件)