自己写的邮件发送功能,可以支持发送内容,发送多个图片和多个附件。
分享给大家,下面是我发送邮件的源码,贴过去用吧
首先准备一个Email对象,用于封装前台传递的数据。(如果你不需要前台的交互,可以不用这个对象)
package com.kewei.emailSender;
import java.io.Serializable;
public class Email implements Serializable {
private String id;
private String sender; // 发送人
private String to; // 发给谁
private String cc; // 抄送人 多个
private String bcc; // 暗送人 多个
private String subject; // 主题
private String sendDate; // 发送时间
private boolean replySign; // 要求回执
private boolean containAttach; // 是否包含附件
private String imagePath; // 邮件图片的路劲 (多个,使用"|"拼接)
private String attachPath; // 邮件附件的路径 (多个,使用"|"拼接)
private String content; // 邮件的文本内容
private boolean isRead; // 是否已读
public Email() {
super();
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public boolean isRead() {
return isRead;
}
public void setRead(boolean isRead) {
this.isRead = isRead;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getTo() {
return to;
}
public void setTo(String to) {
this.to = to;
}
public String getCc() {
return cc;
}
public void setCc(String cc) {
this.cc = cc;
}
public String getBcc() {
return bcc;
}
public void setBcc(String bcc) {
this.bcc = bcc;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getSendDate() {
return sendDate;
}
public void setSendDate(String sendDate) {
this.sendDate = sendDate;
}
public String getImagePath() {
return imagePath;
}
public void setImagePath(String imagePath) {
this.imagePath = imagePath;
}
public String getAttachPath() {
return attachPath;
}
public void setAttachPath(String attachPath) {
this.attachPath = attachPath;
}
public boolean isReplySign() {
return replySign;
}
public void setReplySign(boolean replySign) {
this.replySign = replySign;
}
public boolean isContainAttach() {
return containAttach;
}
public void setContainAttach(boolean containAttach) {
this.containAttach = containAttach;
}
public String getSender() {
return sender;
}
public void setSender(String sender) {
this.sender = sender;
}
}
根据类的单一职能原则,再准备一个EmailMessage对象,辅助邮件进行发送
package com.kewei.emailSender;
import java.io.Serializable;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
public class EmailMessage implements Serializable{
private Email email; //邮件
//private HttpServletRequest request;
private String emailAccount; //发件人
private String receiver; //收件人
private String protocol; //使用协议
private String host; //邮箱服务器
private String auth; //是否请求认证
private String username; //用户名
private String password; //密码
private String cc; // 抄送
private String bcc; // 暗送
private String subject; // 主题
private String charset; // 字符编码
private boolean receipt; // 回执
private String content; // 文本
private Map<String, String> map=new HashMap<String, String>(); //发送邮件处理图片所需的内容
private List<String> attacPaths; //发送邮件附件
/**
* @return protocol
*/
public String getProtocol() {
return "smtp";
}
/**
* @param protocol
*/
public void setProtocol(String protocol) {
this.protocol = protocol;
}
/**
* @return host
*/
public String getHost() {
return EmailUtils.getMailServerHost(email.getSender());
}
/**
* @param host
*/
public void setHost(String host) {
this.host = host;
}
/**
* @return auth
*/
public String getAuth() {
return "true";
}
/**
* @param auth
*/
public void setAuth(String auth) {
this.auth = auth;
}
/**
* @return username
*/
public String getUsername() {
return this.username;
}
/**
* @param username
*/
public void setUsername(String username) {
this.username = username;
}
/**
* @return password
*/
public String getPassword() {
return this.password;
}
/**
* @param password
*/
public void setPassword(String password) {
this.password = password;
}
/**
* @return cc
*/
public String getCc() {
return email.getCc();
}
/**
* @param cc
*/
public void setCc(String cc) {
this.cc = cc;
}
/**
* @return bcc
*/
public String getBcc() {
return email.getBcc();
}
/**
* @param bcc
*/
public void setBcc(String bcc) {
this.bcc = bcc;
}
/**
* @return subject
*/
public String getSubject() {
return email.getSubject();
}
/**
* @param subject
*/
public void setSubject(String subject) {
this.subject = subject;
}
/**
* @return charset
*/
public String getCharset() {
return "UTF-8";
}
/**
* @param charset
*/
public void setCharset(String charset) {
this.charset = charset;
}
public boolean isReceipt() {
return email.isReplySign();
}
public void setReceipt(boolean receipt) {
this.receipt = receipt;
}
/**
* @return content
*/
public String getContent() {
if(map==null||map.size()==0){
return email.getContent();
}
return content;
}
/**
* @param content
*/
public void setContent(String content) {
this.content = content;
}
/**
* @return emailAccount
*/
public String getEmailAccount() {
return email.getSender();
}
/**
* @param emailAccount
*/
public void setEmailAccount(String emailAccount) {
this.emailAccount = emailAccount;
}
/**
* @return receiver
*/
public String getReceiver() {
return email.getTo();
}
/**
* @param receiver
*/
public void setReceiver(String receiver) {
this.receiver = receiver;
}
public Map<String, String> getMap() {
//如果图片路径为null,直接返回null
if(email.getImagePath()==null||"".equals(email.getImagePath().trim())){
return null;
}
StringBuffer sb=new StringBuffer();
sb.append(email.getContent());
//处理邮件中图片和附件的路径
for (String realImgPath : email.getImagePath().split("\\|")) {
String cid=genPK();
// String cid=System.currentTimeMillis()+"";
map.put(realImgPath, cid);
sb.append("<br/><img src='cid:").append(cid).append("'").append("/>");
}
//设置文本
setContent(sb.toString());
return map;
}
public void setMap(Map<String, String> map) {
this.map = map;
}
public List<String> getAttacPaths() {
//如果附件路径为null,直接返回null
if(email.getAttachPath()==null||"".equals(email.getAttachPath().trim())){
return null;
}
List<String> attachList=new ArrayList<String>();
for (String realAttachPath : email.getAttachPath().split("\\|")) {
attachList.add(realAttachPath);
}
return attachList;
}
public EmailMessage(Email email) {
super();
this.email = email;
}
public static String genPK() {
return new BigInteger(165, new Random()).toString(36).toUpperCase();
}
}
提供一个EmailUtils 工具类,用于获取邮件服务器和验证邮件地址
package com.kewei.emailSender;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* @Description: 处理邮件的工具类
* @author huhao
* @date Dec 26, 2013 5:32:38 PM
*/
public class EmailUtils {
private static Log logger = LogFactory.getLog(EmailUtils.class);
// huhao19920306@163.com 通过@之后的是163还是qq,动态的判断邮件服务器pop.163.com
// 994822422@qq.com
public static String getMailServerHost(String emailAddress) {
if (emailAddress == null || "".equals(emailAddress.trim())) {
throw new RuntimeException("邮件账户错误!");
}
StringBuffer sb = new StringBuffer();
sb.append("smtp.");
emailAddress = emailAddress
.substring(emailAddress.lastIndexOf("@") + 1);
sb.append(emailAddress);
return sb.toString().trim();
}
// 验证邮箱地址
public static boolean checkEmail(String email) {
boolean flag = false;
try {
//String check = "^([a-z0-9A-Z]+[-|_|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
String check = "^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\\.[a-zA-Z0-9_-]{2,3}){1,2})$";
Pattern regex = Pattern.compile(check);
Matcher matcher = regex.matcher(email);
flag = matcher.matches();
} catch (Exception e) {
logger.error("邮箱地址错误!");
flag = false;
}
return flag;
}
public static void main(String[] args) {
System.out.println(checkEmail("1@163.ke.com"));
}
}
最后是一个邮件发送对象EmailSender,发送邮件就交给它了
package com.kewei.emailSender;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Map.Entry;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;
/**
* @decrisption 实现邮件的发送
* @author huhao
* @version Nov 19, 2013 11:47:47 AM
* @since JDK1.6.0_10 spring3.2.0
*/
public class MailSender {
private MimeMessage msg;
/**
* @param msg
*/
private EmailMessage emailMessage;
public MailSender() {
super();
}
/**
*
* 发送邮件,可发送多个图片和附件
* @author huhao
* @date Nov 19, 2013 10:25:44 AM
* @param ms
* @throws EmailSendException
* @throws UnsupportedEncodingException
*
*/
public void sendEmail(EmailMessage ms) {
try {
//得到环境对象
getMimeMessage(ms);
msg.setFrom(new InternetAddress(ms.getEmailAccount()));
String [] receiverArray=ms.getReceiver().trim().split(",|,");
//收件人InternetAddress数组
InternetAddress [] receiverAddressArray=new InternetAddress[receiverArray.length];
for (int i = 0; i < receiverArray.length; i++) {
receiverAddressArray[i] =new InternetAddress(receiverArray[i].trim());
}
msg.setRecipients(MimeMessage.RecipientType.TO, receiverAddressArray); //设置收件人
//暗送
if(ms.getBcc()!=null && !"".equals(ms.getBcc().trim())){
String [] bccArray=ms.getBcc().trim().split(",|,");
InternetAddress [] bccAddressArray=new InternetAddress[bccArray.length];
for (int i = 0; i < bccArray.length; i++) {
bccAddressArray[i] =new InternetAddress(bccArray[i].trim());
}
msg.setRecipients(MimeMessage.RecipientType.BCC, bccAddressArray);
}
//抄送
if(ms.getCc()!=null && !"".equals(ms.getCc().trim())){
String [] ccArray=ms.getCc().trim().split(",|,");
InternetAddress [] ccAddressArray=new InternetAddress[ccArray.length];
for (int i = 0; i < ccArray.length; i++) {
ccAddressArray[i] =new InternetAddress(ccArray[i].trim());
}
msg.setRecipients(MimeMessage.RecipientType.CC, ccAddressArray);
}
if(ms.isReceipt()){ //是否要求回执
msg.setHeader("Disposition-Notification-To","1");
msg.addHeader("Disposition-Notification-To", "1");
}
msg.setSubject(ms.getSubject()); //主题
MimeMultipart mmp = new MimeMultipart();
Map<String, String> map=ms.getMap();
//得到邮件内容
if(map==null){
mmp.addBodyPart(getTextPart(ms.getContent(), ms.getCharset()));
}
//得到所有的图片
if(map!=null){
mmp.addBodyPart(getTextPart(ms.getContent(), ms.getCharset()));
List<MimeBodyPart> imageParts=getImageParts(map);
for (MimeBodyPart imagePart : imageParts) {
mmp.addBodyPart(imagePart);
}
}
//得到所有的附件
List<String> attachPaths =ms.getAttacPaths();
if(attachPaths!=null){
List<MimeBodyPart> attchParts=getAttachmentParts(attachPaths);
for (MimeBodyPart attchPart : attchParts) {
mmp.addBodyPart(attchPart);
}
}
msg.setSentDate(new Date());
mmp.setSubType("mixed");
msg.setContent(mmp);
msg.saveChanges();//保存修改
//发送邮件
Transport.send(msg);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
*
* 得到邮件的环境对象
* @author huhao
* @date Nov 19, 2013 10:13:57 AM
*/
public void getMimeMessage(EmailMessage ms){
Properties props = new Properties();//设置一些参数:发送时需要设置
props.setProperty("mail.transport.protocol", ms.getProtocol());
props.setProperty("mail.host", ms.getHost());
props.setProperty("mail.smtp.auth", ms.getAuth());//请求认证
final String username=ms.getUsername();
final String password=ms.getPassword();
Session session = Session.getInstance(props,new Authenticator(){
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username,password);
}
});//代表环境的对象
msg = new MimeMessage(session);//得到了代表邮件的对象
}
/**
*
* 得到文本部分
* @author huhao
* @date Nov 19, 2013 11:05:16 AM
* @param content 文本内容(html代码)
* @param charset 字符编码
* @return
* @throws MessagingException
*
*/
public MimeBodyPart getTextPart(String content,String charset) throws MessagingException{
MimeBodyPart textPart = new MimeBodyPart();
textPart.setContent(content, "text/html;charset="+charset);
return textPart;
}
/**
*
* 得到图片部分
* @author huhao
* @date Nov 19, 2013 11:18:19 AM
* @param map 代表的是文件路径和它所在的img标签的cid
* @return
* @throws MessagingException
*
*/
public List<MimeBodyPart> getImageParts(Map<String ,String> map) throws MessagingException{
List<MimeBodyPart> imageParts=new ArrayList<MimeBodyPart>();
for(Entry<String , String> e :map.entrySet()){
MimeBodyPart imagePart = new MimeBodyPart();
DataHandler dh = new DataHandler(new FileDataSource(e.getKey())); //jaf会自动探测文件的MIME类型
imagePart.setDataHandler(dh);
imagePart.setContentID(e.getValue());
imageParts.add(imagePart);
}
return imageParts;
}
/**
*
* 得到附件部分
* @author huhao
* @date Nov 19, 2013 11:22:36 AM
* @param sources 多个附件的路径
* @return
* @throws MessagingException
* @throws UnsupportedEncodingException
*
*/
public List<MimeBodyPart> getAttachmentParts(List<String> sources) throws MessagingException, UnsupportedEncodingException{
List<MimeBodyPart> attachmentParts=new ArrayList<MimeBodyPart>();
for (String source : sources) {
MimeBodyPart attachmentPart = new MimeBodyPart();
DataHandler dh = new DataHandler(new FileDataSource(source));//jaf会自动探测文件的MIME类型
String name = dh.getName();
attachmentPart.setDataHandler(dh);
attachmentPart.setFileName(MimeUtility.encodeText(name.substring(name.lastIndexOf("$^%")+3)));
attachmentParts.add(attachmentPart);
}
return attachmentParts;
}
}
那么如何调用MailSender进行邮件的发送呢?
如果你需要和前端进行交互,可以使用email对象进行封装数据,在将email对象传递个emailMessage对象。
如果不需要的话,你可以修改一下我的代码。直接将数据传递给emailmessage对象。进行邮件的发送