Java Email 的简单使用
其它:Spring 中 Environment 的用法
一、Commons-Email 的使用:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-email</artifactId>
<version>1.4</version>
</dependency>
/**
* 邮件信息类
* @author fmr
*/
public class EmailInfo {
//发件人
private String fromAddress;
//发件人昵称
private String fromNickName;
// 收件人
private List<String> toAddress = null;
// 抄送人地址
private List<String> ccAddress = null;
// 密送人
private List<String> bccAddress = null;
// 附件信息
private List<EmailAttachment> attachments = null;
// 邮件主题
private String subject;
// 邮件的文本内容
private String content;
}
/**
* 发送邮件工具类
* @author fmr
*
*/
public class MailUtil {
private static final String hostName = "smtp.126.com";
private static final String userInfo = "******"; //服务器验证码 -- 非发件人邮箱密码
private static final String chartset = "UTF-8";
/**
* 发送 邮件方法 (Html格式,支持附件)
* @return void
*/
public static void sendEmail(EmailInfo mailInfo) {
try {
HtmlEmail email = new HtmlEmail();
// 配置信息
email.setHostName(hostName);
email.setFrom(mailInfo.getFromAddress(),mailInfo.getFromNickName());
email.setAuthentication(mailInfo.getFromAddress(),userInfo);
email.setCharset(chartset);
email.setSubject(mailInfo.getSubject());
email.setHtmlMsg(mailInfo.getContent());
// 添加附件
List<EmailAttachment> attachments = mailInfo.getAttachments();
if (null != attachments && attachments.size() > 0) {
for(EmailAttachment emailAttachment : attachments) {
email.attach(emailAttachment);
}
}
// 收件人
List<String> toAddress = mailInfo.getToAddress();
if (null != toAddress && toAddress.size() > 0) {
for (int i = 0; i < toAddress.size(); i++) {
email.addTo(toAddress.get(i));
}
}
// 抄送人
List<String> ccAddress = mailInfo.getCcAddress();
if (null != ccAddress && ccAddress.size() > 0) {
for (int i = 0; i < ccAddress.size(); i++) {
email.addCc(ccAddress.get(i));
}
}
//邮件模板 密送人
List<String> bccAddress = mailInfo.getBccAddress();
if (null != bccAddress && bccAddress.size() > 0) {
for (int i = 0; i < bccAddress.size(); i++) {
email.addBcc(ccAddress.get(i));
}
}
//发送
email.send();
} catch (EmailException e) {
e.printStackTrace();
}
}
}
/**
* 邮件 测试
* @author fmr
*
*/
public class EmailController {
public static void main(String[] args) {
EmailInfo info = new EmailInfo();
//发件人
info.setFromAddress("[email protected]");
//收件人
List<String> toAddress = new ArrayList<String>();
toAddress.add("[email protected]");
info.setToAddress(toAddress);
//发件人昵称
info.setFromNickName("张三");
//主题
info.setSubject("邮件测试");
//内容
info.setContent("<h1>邮件测试内容...</h1>");
//添加附件
EmailAttachment att = new EmailAttachment();
att.setPath("C:\\Users\\fmr\\Desktop\\7.png");
att.setName("测试.png");
List<EmailAttachment> atts = new ArrayList<EmailAttachment>();
atts.add(att);
info.setAttachments(atts);
//发送
MailUtil.sendEmail(info);
}
}