前言
在我们日常工作中,邮件发送服务经常会用到,我们常用的java邮件服务实现方案有:java原生自带的javamail、apache commons mail工具包、spring mail。但是个人使用这么久而言,感觉使用起来都不太顺手,也略显复杂
在此推荐一个简单易用的类库simple-java-mail
github地址: http://www.simplejavamail.org
下面我会介绍一下这个mail工具类的基本用法,不过基本都是来自于官网,随后我会基于这个mail工具类去封装一个基本通用的邮件服务。
maven引入
<dependency> <groupId>org.simplejavamail</groupId> <artifactId>simple-java-mail</artifactId> <version>4.2.3-java6-release</version> </dependency>
例子
发送一封简易邮件
写法1 Builder模式:
Email email = new EmailBuilder()
.from("Michel Baker", "m.baker@mbakery.com")
.to("mom", "jean.baker@hotmail.com")
.to("dad", "StevenOakly1963@hotmail.com")
.subject("My Bakery is finally open!")
.text("Mom, Dad. We did the opening ceremony of our bakery!!!")
.build();new Mailer("server", 25, "username", "password").sendMail(email);
写法二 常规模式:
Email email = new Email();
email.setFromAddress("Michel Baker", "m.baker@mbakery.com");
email.addRecipient("mom", "jean.baker@hotmail.com", RecipientType.TO);
email.addRecipient("dad", "StevenOakly1963@hotmail.com", RecipientType.TO);
email.setSubject("My Bakery is finally open!");
email.setText("Mom, Dad. We did the opening ceremony of our bakery!!!");new Mailer("server", 25, "username", "password").sendMail(email);
和spring结合使用
<bean id="inhouseMailer" class="org.simplejavamail.mailer.Mailer"> <constructor-arg value="server" /> <constructor-arg value="25" /> <constructor-arg value="username" /> <constructor-arg value="password" /> </bean> @Autowired Mailer inhouseMailer; inhouseMailer.sendMail(email); inhouseMailer.sendMail(anotherEmail);
添加多个接收者
//添加多个接收者
email.addRecipients(yourRecipient1, yourRecipient2...);
//也可以通过逗号“,”分割多个抄送人
String list = "twister@sweets.com,blue.tongue@sweets.com;honey@sweets.com";
emailNormal.addRecipients(list, RecipientType.BCC);builder模式:
.to(yourRecipient1, yourRecipient2...)
.bcc("twister@sweets.com,blue.tongue@sweets.com;honey@sweets.com")
...
.build();
支持异步发送
// 第二个参数是true则是异步发送,false则是同步发送
mailer.sendMail(email, true);
配置SSL或TLS
Email email = new Email();
mailer.sendMail(email, TransportStrategy.SMTP_PLAIN); // 此为默认值,不加嵌套任何传输协议
mailer.sendMail(email, TransportStrategy.SMTP_SSL);
mailer.sendMail(email, TransportStrategy.SMTP_TLS);
我们也可以在初始化邮件服务器配置时声明传输协议
new Mailer("smtp.gmail.com", 25, "your user", "your password", TransportStrategy.SMTP_TLS).sendMail(email);
new Mailer("smtp.gmail.com", 587, "your user", "your password", TransportStrategy.SMTP_TLS).sendMail(email);
new Mailer("smtp.gmail.com", 465, "your user", "your password", TransportStrategy.SMTP_SSL).sendMail(email);
发送附件
Email email = new Email();
email.addAttachment("dresscode.txt", new ByteArrayDataSource("Black Tie Optional", "text/plain"));
email.addAttachment("location.txt", "On the moon!".getBytes(Charset.defaultCharset()), "text/plain");// 当然,你可以传输任何文件格式的附件
email.addAttachment("invitation.pdf", new FileDataSource("invitation_v8.3.pdf"));
内容嵌套图片
Email email = new Email();
email.addEmbeddedImage("smiley", new FileDataSource("smiley.jpg"));
String base64String = "iVBORw0KGgoAAAANSUhEUgAAA ...snip";
email.addEmbeddedImage("thumbsup", parseBase64Binary(base64String), "image/png");// 图片需要在html文本中通过cid:xxxx,的方式引用
<p>Let's go!</p>![](cid:thumbsup)<br/>
<p>Smile!</p>![](cid:smiley)
自定义发送头
Email email = new Email();
email.addHeader("X-Priority", 2);
email.addHeader("X-MC-GoogleAnalyticsCampaign", "halloween_sale");
email.addHeader("X-MEETUP-RECIP-ID", "71415272");
email.addHeader("X-my-custom-header", "foo");
验证邮箱合法性
具体使用的工具类是email-rfc2822-validator
github地址:https://github.com/bbottema/email-rfc2822-validator
//经过使用发现,貌似只是用正则表达式去验证邮箱是否合法
EmailAddressValidator.isValid("your_address@domain.com",
EmailAddressCriteria.RFC_COMPLIANT);
EmailAddressValidator.isValid("your_address@domain.com",
EnumSet.of(EmailAddressCriteria.ALLOW_QUOTED_IDENTIFIERS, EmailAddressCriteria.ALLOW_PARENS_IN_LOCALPART));
使用代理发送
// anonymous proxy
new Mailer(serverConfig, new ProxyConfig("proxy.host.com", 1080));// authenticated proxy
new Mailer(serverConfig, new ProxyConfig("proxy.host.com", 1080, "proxy username", "proxy password"));
总结
此工具类方便易用,简洁明了,而且支持Builder模式链式调用。有兴趣的同学可以尝试使用,个人感觉比原生mail,spring mail等易用,更多用法请自行查看官网例子。至于一开始说到的封装通用的邮件服务,这个由于时间关系,我放到下一次再实现。谢谢大家的支持,如果此文对你有所帮助,请点个赞,谢谢。
https://github.com/bbottema/simple-java-mail/
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持易盾网络。