apache common-email使用

最近在项目中开发中需要用到发送邮件功能,当后台定时任务处理完毕后通知调用者。Java Mail API使用比较麻烦,所以这里采用的是Apache Commons Email,官网地址:http://commons.apache.org/proper/commons-email/,Commons Email API比较简洁高效,学习起来也很快。

1、发送简单文本邮件

Email email = new SimpleEmail();
email.setHostName("smtp.googlemail.com");
email.setSmtpPort(465);
email.setAuthenticator(new DefaultAuthenticator("username", "password"));
email.setSSLOnConnect(true);
email.setFrom("user@gmail.com");
email.setSubject("TestMail");
email.setMsg("This is a test mail ... :-)");
email.addTo("foo@bar.com");
email.send();

2、发送带附件的邮件

// Create the attachment
  EmailAttachment attachment = new EmailAttachment();
  attachment.setPath("mypictures/john.jpg");
  attachment.setDisposition(EmailAttachment.ATTACHMENT);
  attachment.setDescription("Picture of John");
  attachment.setName("John");

  // Create the email message
  MultiPartEmail email = new MultiPartEmail();
  email.setHostName("mail.myserver.com");
  email.addTo("jdoe@somewhere.org", "John Doe");
  email.setFrom("me@apache.org", "Me");
  email.setSubject("The picture");
  email.setMsg("Here is the picture you wanted");

  // add the attachment
  email.attach(attachment);

  // send the email
  email.send();

另外还可以通过任意的链接来将网络上的文件添加到附件中,例如:

// Create the attachment
  EmailAttachment attachment = new EmailAttachment();
  attachment.setURL(new URL("http://www.apache.org/images/asf_logo_wide.gif"));
  attachment.setDisposition(EmailAttachment.ATTACHMENT);
  attachment.setDescription("Apache logo");
  attachment.setName("Apache logo");

  // Create the email message
  MultiPartEmail email = new MultiPartEmail();
  email.setHostName("mail.myserver.com");
  email.addTo("jdoe@somewhere.org", "John Doe");
  email.setFrom("me@apache.org", "Me");
  email.setSubject("The logo");
  email.setMsg("Here is Apache's logo");
  
  // add the attachment
  email.attach(attachment);

  // send the email
  email.send();

3、发送HTML格式的邮件

// Create the email message
  HtmlEmail email = new HtmlEmail();
  email.setHostName("mail.myserver.com");
  email.addTo("jdoe@somewhere.org", "John Doe");
  email.setFrom("me@apache.org", "Me");
  email.setSubject("Test email with inline image");
  
  // embed the image and get the content id
  URL url = new URL("http://www.apache.org/images/asf_logo_wide.gif");
  String cid = email.embed(url, "Apache logo");
  
  // set the html message
  email.setHtmlMsg("<html>The apache logo - <img src=\"cid:"+cid+"\"></html>");

  // set the alternative message
  email.setTextMsg("Your email client does not support HTML messages");

  // send the email
  email.send();

4、发送带图片的HTML格式邮件

// load your HTML email template
  String htmlEmailTemplate = ....

  // define you base URL to resolve relative resource locations
  URL url = new URL("http://www.apache.org");

  // create the email message
  HtmlEmail email = new ImageHtmlEmail();
  email.setDataSourceResolver(new DataSourceResolverImpl(url));
  email.setHostName("mail.myserver.com");
  email.addTo("jdoe@somewhere.org", "John Doe");
  email.setFrom("me@apache.org", "Me");
  email.setSubject("Test email with inline image");
  
  // set the html message
  email.setHtmlMsg(htmlEmailTemplate);

  // set the alternative message
  email.setTextMsg("Your email client does not support HTML messages");

  // send the email
  email.send();

另外,在使用过程中发现Email.addTo一次只能添加一个联系人,如果想发送给多个人的话,需要使用for循环嵌套来实现,以下是一个简单的例子:

public static void main(String[] args){

        String mailList = "abc@163.com;tt@qq.com";

        String[] list = mailList.split(";");
        for(int i=0;list!=null && i<list.length;i++){   //嵌套调用

            sendEmail(list[i]);
        }
    }

    public static void sendEmail(String target) {

        try{
            Email email = new SimpleEmail();
            email.setHostName("smtp.163.com");
            email.setSmtpPort(465);
            email.setAuthenticator(new DefaultAuthenticator("abc@163.com","abc"));
            email.setSSLOnConnect(true);
            email.setFrom("abc@163.com");
            email.addTo(target);

            email.setSubject("Test Mail");
            email.setMsg("This is a test mail");
            email.send();

        }catch (Exception e){
            e.printStackTrace();
        }
    }

基于构造着模式的apache email send

package com.haiziwang.platform.tool.core;

import com.haiziwang.platform.tool.dependency.EmailException;
import com.haiziwang.platform.tool.dependency.HtmlEmail;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by wangzhongbao on 2016/10/21.
 */
public class EmailHelper {
	private static final Log logger = LogFactory.getLog(EmailHelper.class);

	//邮箱host
	private String hostName;

	//发送方账号
	private String authAccount;
	//发送方密码
	private String authPwd;

	//邮件主题
	private String subject;
	//邮件正文html
	private String mailBody;
	//邮件正文text
	private String textMsg;
	//接收人列表
	private List<String> receivers = new ArrayList<String>();
	//抄送人列表
	private List<String> ccReceivers = new ArrayList<String>();
	//密送人列表
	private List<String> bccReceivers = new ArrayList<String>();

	private EmailHelper(Builder b) {
		this.hostName = b.hostName;
		this.authAccount = b.authAccount;
		this.authPwd = b.authPwd;
		this.subject = b.subject;
		this.mailBody = b.mailBody;
		this.textMsg = b.textMsg;
		this.receivers = b.receivers;
		this.ccReceivers = b.ccReceivers;
		this.bccReceivers = b.bccReceivers;
	}


	public boolean send() {
		boolean success = true;
		try {
			sendByNative();
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("mail send fail,errmsg:"+e.toString());
			success = false;
		}
		return success;
	}

	/**
	 * 原始发送,如果有异常会直接往上抛出
	 * @throws EmailException
	 */
	public void sendByNative() throws EmailException {
		HtmlEmail email = new HtmlEmail();
		email.setCharset("UTF-8");
		email.setFrom(authAccount, authAccount);
		email.setAuthentication(authAccount, authPwd);
		email.setHostName((hostName!=null && !"".equals(hostName))?hostName:"smtp.exmail.qq.com");

		for(String r:receivers){
			email.addTo(r, "");
		}

		for(String r:ccReceivers){
			email.addCc(r, "");
		}

		for(String r:bccReceivers){
			email.addBcc(r, "");
		}
		email.setSubject(subject);
		if(null!=mailBody && !"".equals(mailBody)){
			email.setContent(mailBody, "text/html;charset=utf-8");
		}else{
			email.setTextMsg(textMsg);
		}
		email.send();
	}

	//构造着模式,fluence编程风格
	public static class Builder{
		private String hostName;
		private String authAccount;
		private String authPwd;
		private String subject;
		private String mailBody;
		private String textMsg;
		private List<String> receivers = new ArrayList<String>();
		private List<String> ccReceivers = new ArrayList<String>();
		private List<String> bccReceivers = new ArrayList<String>();

		public Builder hostName(String hostName) {
			this.hostName = hostName;
			return this;
		}

		public Builder authAccount(String authAccount){
			this.authAccount = authAccount;
			return this;
		}

		public Builder authPwd(String authPwd){
			this.authPwd = authPwd;
			return this;
		}

		public Builder authentication(String authAccount,String authPwd){
			this.authAccount = authAccount;
			this.authPwd = authPwd;
			return this;
		}

		public Builder subject(String subject){
			this.subject = subject;
			return this;
		}

		public Builder mailBody(String mailBody){
			this.mailBody = mailBody;
			return this;
		}

		public Builder textMsg(String textMsg){
			this.textMsg = textMsg;
			return this;
		}

		public Builder receivers(List<String> receivers){
			this.receivers.addAll(receivers);
			return this;
		}

		public Builder addReceiver(String receiver){
			if(receiver!=null && !"".equals(receiver)){
				String[] receiverArr = receiver.split(",");
				for(String r:receiverArr){
					receivers.add(r);
				}
			}
			return this;
		}

		public Builder ccReceivers(List<String> ccReceivers){
			this.ccReceivers.addAll(ccReceivers);
			return this;
		}

		public Builder addCcReceiver(String ccReceiver){
			if(ccReceiver!=null && !"".equals(ccReceiver)){
				String[] ccReceiverArr = ccReceiver.split(",");
				for(String r:ccReceiverArr){
					ccReceivers.add(r);
				}
			}
			return this;
		}

		public Builder bccReceivers(List<String> bccReceivers){
			this.bccReceivers.addAll(bccReceivers);
			return this;
		}

		public Builder addBccReceiver(String bccReceiver){
			if(bccReceiver!=null && !"".equals(bccReceiver)){
				String[] bccReceiverArr = bccReceiver.split(",");
				for(String r:bccReceiverArr){
					bccReceivers.add(r);
				}
			}
			return this;
		}

		public EmailHelper builder(){
			return new EmailHelper(this);
		}

	}
}


public class Sample {
	/**
	 * TODO未做junit测试,直接写了一个main做单元测试
	 *
	 * @param args
	 */
	public static void main(String[] args) throws EmailException, MalformedURLException {
		new EmailHelper.Builder().authentication("wang_ffag@haiziwang.com", "111111")
				.subject("天气预报").mailBody("<font style='color:red;'>天气不错哦</font>").addReceiver("zhongbao.wang@haiziwang.com").builder().send();
	}
}

转载于:https://my.oschina.net/yiqifendou/blog/776586

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值