發送沒有附件的郵箱:
public void test2() throws Exception{
//1:聲明服務器地址
Properties p = new Properties();
p.setProperty("mail.host","smtp.sohu.com");//指定服務器,以搜狐郵箱為例
p.setProperty("mail.smtp.auth","true");//進行驗證
Authenticator auth = new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("xxxxxx","密碼");
}
};
//2:聲明Session
Session session = Session.getDefaultInstance(p,auth);
//設置為調試模式
session.setDebug(true);
//3:聲明信息
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress("[email protected]"));
msg.setRecipient(RecipientType.TO,new InternetAddress("要發送的郵箱"));
msg.setSubject("標題,誰便");
msg.setContent("內容,自己寫","text/html;charset=UTF-8");
//發送
Transport.send(msg);
}
發送含有附件的郵件:
public void test3() throws Exception{
//1:聲明服務器地址
Properties p = new Properties();
p.setProperty("mail.host","smtp.sohu.com");//指定服務器,以搜狐為例
p.setProperty("mail.smtp.auth","true");//進行驗證
Authenticator auth = new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("xxxxxxx","密碼");
}
};
//2:聲明Session
Session session = Session.getDefaultInstance(p,auth);
//設置為調試模式
session.setDebug(true);
//3:聲明信息
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress("[email protected]"));
msg.setRecipient(RecipientType.TO,new InternetAddress("要發送的郵箱"));
msg.setSubject("大家好1111");
//聲明Multibody
MimeMultipart multi = new MimeMultipart();
//添加一個附件
javax.mail.internet.MimeBodyPart part1 = new javax.mail.internet.MimeBodyPart();
part1.attachFile(new File("文件的地址"));
part1.setFileName(MimeUtility.encodeText("要發送的文件名及後綴"));
multi.addBodyPart(part1);
javax.mail.internet.MimeBodyPart part2 = new javax.mail.internet.MimeBodyPart();
part2.setContent("你好這是內容<b>Hello</b>","text/html;charset=UTF-8");
multi.addBodyPart(part2);
msg.setContent(multi);
Transport.send(msg);
}