设为首页 收藏本站
查看: 586|回复: 0

[经验分享] 简单的邮件发送封装库(1) -- 使用Apache Commons Email

[复制链接]

尚未签到

发表于 2017-1-13 11:19:35 | 显示全部楼层 |阅读模式
package cn.iamsese.product.custom.tools.email;
import java.text.MessageFormat;
import java.util.Enumeration;
import org.apache.commons.mail.Email;
import org.apache.commons.mail.EmailAttachment;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.MultiPartEmail;
import org.apache.commons.mail.SimpleEmail;

/**
* 简单的邮件发送客户端 -- 使用Apache Commons Email
* cn.iamsese.product.custom.tools.email
* Author: vb2005xu [JAVA菜鸟]
*/
public class SimpleEmailClient {
private Email emailTranslate ; //email 传输器对象 , 可以为SimpleEmail 和 MultiPartEmail 作为实现对象
public SimpleEmailClient() {
this.setEmailTranslate(new SimpleEmail());
}
public SimpleEmailClient(boolean isMultiPartEmail) {
if (isMultiPartEmail)
this.setEmailTranslate(new MultiPartEmail());
else
this.setEmailTranslate(new SimpleEmail());
}
private String smtpHost, smtpUser, smtpPassword;
public Email getEmailTranslate() {
return emailTranslate;
}
public void setEmailTranslate(Email emailTranslate) {
this.emailTranslate = emailTranslate;
}
public String getSmtpUser() {
return smtpUser;
}
private void setSmtpUser(String smtpUser) {
this.smtpUser = smtpUser;
}
public String getSmtpPassword() {
return smtpPassword;
}
private void setSmtpPassword(String smtpPassword) {
this.smtpPassword = smtpPassword;
}
public String getSmtpHost() {
return smtpHost;
}
public void setSmtpHost(String smtpHost) {
this.smtpHost = smtpHost;
}
public void setSmtpAuthentication(String smtpUser, String smtpPassword) {
this.setSmtpUser(smtpUser);
this.setSmtpPassword(smtpPassword);
}
@SuppressWarnings("finally")
public boolean sendTextEmail(SimpleEmailObject emailObj) {
boolean sendState = false;
SimpleEmail simpleEmailTranslate = (SimpleEmail) this.getEmailTranslate();
simpleEmailTranslate.setHostName(this.getSmtpHost());
simpleEmailTranslate.setAuthentication(this.getSmtpUser(),
this.getSmtpPassword());
simpleEmailTranslate.setCharset(emailObj.getCharset());
try {
simpleEmailTranslate.addTo(emailObj.getTo(),
emailObj.getReciverName());
simpleEmailTranslate.setFrom(emailObj.getFrom(),
emailObj.getSenderName());
simpleEmailTranslate.setSubject(emailObj.getSubject());
simpleEmailTranslate.setMsg(emailObj.getMessage());
simpleEmailTranslate.send();
sendState = true;
} catch (EmailException e) {
//
} finally {
return sendState;
}
}
@SuppressWarnings("finally")
public boolean sendMultiPartEmail(MultiPartEmailObject emailObj) {
boolean sendState = false;
MultiPartEmail multiPartEmailTranslate = (MultiPartEmail) this.getEmailTranslate();
multiPartEmailTranslate.setHostName(this.getSmtpHost());
multiPartEmailTranslate.setAuthentication(this.getSmtpUser(),
this.getSmtpPassword());
multiPartEmailTranslate.setCharset(emailObj.getCharset());
try {
//添加附件
Enumeration<EmailAttachmentObject> attachments = emailObj.getAttachments().elements();
while (attachments.hasMoreElements()){
EmailAttachment attachment = attachments.nextElement().getEmailAttachment() ;
if (attachment != null && attachment instanceof EmailAttachment)
multiPartEmailTranslate.attach(attachment);
}
multiPartEmailTranslate.addTo(emailObj.getTo(),
emailObj.getReciverName());
multiPartEmailTranslate.setFrom(emailObj.getFrom(),
emailObj.getSenderName());
multiPartEmailTranslate.setSubject(emailObj.getSubject());
multiPartEmailTranslate.setMsg(emailObj.getMessage());
multiPartEmailTranslate.send();
sendState = true;
} catch (EmailException e) {
//
} finally {
return sendState;
}
}
private final String tipInfoFormat = "{5} \nTime: {4,date,full} {4,time,full} \nTo: {0} \nFrom: {1} \nSubject: {2} \nMessage: {3}";
public String getErrorInfo(SimpleEmailObject emailObj) {
// Assert.verify(s.equals(""));
return MessageFormat.format(this.tipInfoFormat, emailObj.getTo(),
emailObj.getFrom(), emailObj.getSubject(), emailObj
.getMessage(), new java.util.Date(), "邮件发送失败<?>");
}
public String getSuccessInfo(SimpleEmailObject emailObj) {
return MessageFormat.format(this.tipInfoFormat, emailObj.getTo(),
emailObj.getFrom(), emailObj.getSubject(), emailObj
.getMessage(), new java.util.Date(), "邮件发送成功<!!> ");
}

public static void main(String[] args) {
//SimpleEmailClient emailClient = new SimpleEmailClient();
SimpleEmailClient emailClient = new SimpleEmailClient(true);
emailClient.setSmtpHost("smtp.sina.com");
emailClient.setSmtpAuthentication("vb2005xu", "123456");
//emailClient.testSendTextEmail(emailClient);
emailClient.testSendMultiPartEmail(emailClient);
}
public String getTipInfoFormat() {
return tipInfoFormat;
}
public void testSendTextEmail(SimpleEmailClient emailClient) {
SimpleEmailObject emailObj = new SimpleEmailObject();
emailObj.setCharset("UTF-8");
emailObj.setTo("vb2005xu@sina.com");
emailObj.setReciverName("色色");
emailObj.setFrom("iamsese@hklm.com");
emailObj.setSenderName("会潜水的猪");
emailObj.setSubject("文本Email测试: ");
emailObj.setMessage("纯文本信息" + this.getClass().getName());
if (emailClient.sendTextEmail(emailObj)) {
System.out.println(emailClient.getSuccessInfo(emailObj));
System.out.println("--------------------------------");
} else {
System.out.println(emailClient.getErrorInfo(emailObj));
System.out.println("--------------------------------");
}
}

public void testSendMultiPartEmail(SimpleEmailClient emailClient) {
MultiPartEmailObject emailObj = new MultiPartEmailObject();
emailObj.setCharset("UTF-8");
emailObj.setTo("vb2005xu@sina.com");
emailObj.setReciverName("色色");
emailObj.setFrom("momo@hklm.com");
emailObj.setSenderName("默默");
emailObj.setSubject("默默相片附件测试: ");
String[] attachmentIDs = new String[5];
attachmentIDs[0] = emailObj.addAttachment(null, new EmailAttachmentObject("默默","E:\\momo.jpg","默默的相片",false));
attachmentIDs[1] = emailObj.addAttachment(null, new EmailAttachmentObject("默默","E:\\momo.jpg","默默的相片",false));
attachmentIDs[2] = emailObj.addAttachment(null, new EmailAttachmentObject("默默","E:\\momo.jpg","默默的相片",true));
attachmentIDs[3] = emailObj.addAttachment(null, new EmailAttachmentObject("默默","E:\\momo.jpg","默默的相片",false));
attachmentIDs[4] = emailObj.addAttachment(null, new EmailAttachmentObject("默默","E:\\momo.jpg","默默的相片",false));
emailObj.setMessage("图片附件信息: " + emailObj.getAttachments().size());
if (emailClient.sendMultiPartEmail(emailObj)) {
System.out.println(emailClient.getSuccessInfo(emailObj));
System.out.println("--------------------------------");
for (String attachmentID : attachmentIDs)
System.out.println("附件ID: " + attachmentID);
System.out.println("--------------------------------");
} else {
System.out.println(emailClient.getErrorInfo(emailObj));
System.out.println("--------------------------------");
for (String attachmentID : attachmentIDs)
System.out.println("附件ID: " + attachmentID);
System.out.println("--------------------------------");
}
}
}


package cn.iamsese.product.custom.tools.email;
/**
* 简单的 Email 对象 ,一个 pojo类
* cn.iamsese.product.custom.tools.email
* Author: vb2005xu [JAVA菜鸟]
*/
public class SimpleEmailObject {
private String to, from, subject, message;
private String senderName, reciverName;
private String charset ;
public String getTo() {
return to;
}
public void setTo(String to) {
this.to = to;
}
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getSenderName() {
return senderName;
}
public void setSenderName(String senderName) {
this.senderName = senderName;
}
public String getReciverName() {
return reciverName;
}
public void setReciverName(String reciverName) {
this.reciverName = reciverName;
}
public String getCharset() {
return charset;
}
public void setCharset(String charset) {
this.charset = charset;
}
}


package cn.iamsese.product.custom.tools.email;
import java.util.Hashtable;
//import org.apache.commons.mail.EmailAttachment;
/**
* 支持附件的 Email源对象 -- 支持 动态操作附件
* cn.iamsese.product.custom.tools.email
* Author: vb2005xu [JAVA菜鸟]
*/
public class MultiPartEmailObject extends SimpleEmailObject {
/**
* 附件列表 -- org.apache.commons.mail.EmailAttachment 对象
*/
private Hashtable<String, EmailAttachmentObject> attachments ;
public MultiPartEmailObject(){
this.setAttachments(new Hashtable<String, EmailAttachmentObject>());
}
/**
* 添加一个指定名称的附件到列表中 -- 返回附件的id
* 未指定id的将由系统来随机生成
* @param attachmentID
* @param attachment
* @return
*/
public String addAttachment(String attachmentID,EmailAttachmentObject attachment){
attachmentID = this.varityAttachmentID(attachmentID);
if (attachmentID == null){
//attachmentID = String.valueOf(System.currentTimeMillis()) ;
attachmentID = String.valueOf(System.currentTimeMillis()) + '@' + Integer.toHexString(attachment.hashCode()) ;
}
if (attachment != null && attachment instanceof EmailAttachmentObject){
this.getAttachments().put(attachmentID,attachment);
return attachmentID ;
}
return null ;
}
/**
* 验证 附件id的方法 -- 因为多个方法要求使用
* @param attachmentID
* @return
*/
private String varityAttachmentID(String attachmentID){
if (attachmentID == null){
return null ;
}
attachmentID = attachmentID.trim();
if ("".equals(attachmentID)){
return null ;
}
if (! this.getAttachments().containsKey(attachmentID) ){
return null ;
}
return attachmentID ;
}
/**
* 通过 附件id移除一个附件 -- 成功则返回被删除附件的id
* @param attachmentID
* @return
*/
public String removeAttachmentByID(String attachmentID){
attachmentID = this.varityAttachmentID(attachmentID);
if (attachmentID != null){
this.getAttachments().remove(attachmentID);
return attachmentID ;
}
return null ;
}
/**
* 通过 附件id 查找 附件
* @param attachmentID
* @return
*/
public EmailAttachmentObject getAttachmentByID(String attachmentID){
attachmentID = this.varityAttachmentID(attachmentID);
if (attachmentID != null){
//这里不用强制转换是因为 使用了 哈希表的泛型定义
return this.getAttachments().get(attachmentID);
}
return null ;
}
public Hashtable<String, EmailAttachmentObject> getAttachments() {
return attachments;
}
public void setAttachments(Hashtable<String, EmailAttachmentObject> attachments) {
this.attachments = attachments;
}

}


package cn.iamsese.product.custom.tools.email;
import org.apache.commons.mail.EmailAttachment;
/**
* Email 附件对象封装类
* cn.iamsese.product.custom.tools.email
* Author: vb2005xu [JAVA菜鸟]
*/
public class EmailAttachmentObject {
private String desc , name , path ;
private boolean isInLine ; //缺省为false
public EmailAttachmentObject(){}
public EmailAttachmentObject(String name ,String path ,String desc , boolean isInLine){
this.setName(name);this.setPath(path);this.setDesc("");this.setInLine(isInLine);
}
/**
* 初始化 , 防止 传入的参数 不达标
*/
private void init(){
this.name = (name != null && ! "".equals(name.trim())) ? name : "" ;
this.path = (path != null && ! "".equals(path.trim())) ? path : "" ;
this.desc = (desc != null && ! "".equals(desc.trim())) ? path : "" ;
}
/**
* 获取 邮件附件对象
* @return
*/
public EmailAttachment getEmailAttachment(){
this.init();
EmailAttachment attachment = null ;
if (! "".equals(this.getPath()) ){
attachment = new EmailAttachment();
attachment.setPath(this.getPath());
attachment.setDescription(this.getDesc());
attachment.setDisposition(this.getDisposition());
attachment.setName(this.getName());
}
return attachment ;
}
public void setInLine(boolean isInLine) {
this.isInLine = isInLine;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDisposition() {
return (isInLine) ? EmailAttachment.INLINE : EmailAttachment.ATTACHMENT ;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
}

  出现了邮件附件名称乱码的问题,见图

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-327946-1-1.html 上篇帖子: 开源的许可证GPL、LGPL、BSD、Apache 2.0的通俗解释 下篇帖子: 开源软件授权协议详解(GPL/MPL/LGPL/BSD/Apache Licence/Creative Commons/MIT)
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表