JavaMail学习笔记(三)、使用SMTP协议发送电子邮件(全)(三)

2014-11-24 08:17:23 · 作者: · 浏览: 3
mlPart.setContent(htmlMultipart);
MimeBodyPart htmlContent = new MimeBodyPart();
htmlContent.setContent(
"这是我自己用java mail发送的邮件哦!" +
"
"
, "text/html;charset=gbk");
htmlMultipart.addBodyPart(htmlContent);

// 保存邮件内容修改
message.saveChanges();

/*File eml = buildEmlFile(message);
sendMailForEml(eml);*/

// 发送邮件
Transport.send(message);
}

/**
* 将邮件内容生成eml文件
* @param message 邮件内容
*/
public static File buildEmlFile(Message message) throws MessagingException, FileNotFoundException, IOException {
File file = new File("c:\\" + MimeUtility.decodeText(message.getSubject())+".eml");
message.writeTo(new FileOutputStream(file));
return file;
}

/**
* 发送本地已经生成好的email文件
*/
public static void sendMailForEml(File eml) throws Exception {
// 获得邮件会话
Session session = Session.getInstance(props,new MyAuthenticator());
// 获得邮件内容,即发生前生成的eml文件
InputStream is = new FileInputStream(eml);
MimeMessage message = new MimeMessage(session,is);
//发送邮件
Transport.send(message);
}

/**
* 向邮件服务器提交认证信息
*/
static class MyAuthenticator extends Authenticator {

private String username = "xyang0917";

private String password = "123456abc";

public MyAuthenticator() {
super();
}

public MyAuthenticator(String username, String password) {
super();
this.username = username;
this.password = password;
}

@Override
protected PasswordAuthentication getPasswordAuthentication() {

return new PasswordAuthentication(username, password);
}
}
}
测试结果:

1、发送文本邮件


2、发送简单的html邮件


3、发送带内嵌图片的HTML邮件


4、发送混合组合邮件



作者:xyang81