前言
demo灵感来自一次无畏的面试经历:
在曾经的一次面试过程中,技术面试官问到了,邮件发送相关的问题,当时的回答完全不匹配自己三年之余的开发经验,a lesson,所以决定将 javamail 几种邮件发送方式都攻一下。
所有示例均使用QQ邮箱服务器codeing
一、准备工作
1、需要设置QQ邮箱-开启smtp
2、如果不想使用独立密码,可以直接使用授权码
二、引入apache依赖
org.apache.commons
commons-email
1.5
三、配置文件
public class EmailConstants {
public static final String EMAIL_HOST = "smtp.qq.com";
public static final int EMAIL_PORT = 456;
public static final String AUTHOR_USER = "";
public static final String RECEIVE_USER = "";
//QQ授权码
public static final String AUTHOR_PWD = "";
public static final String[] CLZZ_NAME = { "ImageHtmlEmail", "SimpleEmail", "HtmlEmail", "MultiPartEmail" };
}
四、工具类public static Email constrator(Class clzz) throws EmailException {
Email email = null;
String clzzs = String.valueOf(clzz);
email = getInstance(email, clzzs);
initEmails(email);
return email;
}
private static Email getInstance(Email email, String clzzs) {
int i = 0;
while (!clzzs.contains(EmailConstants.CLZZ_NAME[i])) {
i++;
}
switch (EmailConstants.CLZZ_NAME[i]) {
case "ImageHtmlEmail":
email = new ImageHtmlEmail();
break;
case "SimpleEmail":
email = new SimpleEmail();
break;
case "HtmlEmail":
email = new HtmlEmail();
break;
case "MultiPartEmail":
email = new MultiPartEmail();
break;
default:
break;
}
return email;
}
private static void initEmails(Email email) throws EmailException {
email.setHostName(EmailConstants.EMAIL_HOST);
email.setAuthentication(EmailConstants.AUTHOR_USER, EmailConstants.AUTHOR_PWD);
email.setFrom(EmailConstants.AUTHOR_USER);
email.setSmtpPort(EmailConstants.EMAIL_PORT);
email.setSSLOnConnect(true);
email.setCharset("UTF-8");
}
至此,javamail工具已经完成。
项目结构:
1、测试普通文字结果
2、测试附件发送
3、测试html发送
4、测试imagehtml发送
看到这里大家会有疑问,hmtl邮件和imagehtml邮件有什么区别,当然会有区别,html邮件只能发送http请求求的图片,后者则可以发送本地的,demo中也会有详细说明