java的邮箱发送工具类

package com.zhensheng.keji.common.utils;


import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
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;


import com.zhensheng.keji.common.config.Global;


/**
 * 发送邮件的util类
 * 
 */
public class EmailUtil {


/**
* 发送邮件
*
* 待发送的邮件的信息
*/
public boolean sendMail() {
// 判断是否需要身份认证
MyAuthenticator authenticator = null;
Properties pro = mailInfo.getProperties();
if (mailInfo.isValidate()) {
// 如果需要身份认证,则创建一个密码验证器
authenticator = new MyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());
}
// 根据邮件会话属性和密码验证器构造一个发送邮件的session
Session sendMailSession = Session.getDefaultInstance(pro, authenticator);
try {
// 根据session创建一个邮件消息
Message mailMessage = new MimeMessage(sendMailSession);
// 创建邮件发送者地址
Address from = new InternetAddress(mailInfo.getFromAddress());
// 设置邮件消息的发送者
mailMessage.setFrom(from);
// 创建邮件的接收者地址,并设置到邮件消息中
String toList = null;
String toListcs = null;
String toListms = null;


if (mailInfo.getToAddress() != null) {
toList = getMailList(mailInfo.getToAddress());
InternetAddress[] iaToList = new InternetAddress().parse(toList);
mailMessage.setRecipients(Message.RecipientType.TO, iaToList); // 收件人
}
if (mailInfo.getCsAddress() != null) {
toListcs = getMailList(mailInfo.getCsAddress());
InternetAddress[] iaCsList = new InternetAddress().parse(toListcs);
mailMessage.setRecipients(Message.RecipientType.CC, iaCsList); // 收件人
}
// 密送
if (mailInfo.getMsAddress() != null) {
toListms = getMailList(mailInfo.getMsAddress());
InternetAddress[] iaToListms = new InternetAddress().parse(toListms);
mailMessage.setRecipients(Message.RecipientType.BCC, iaToListms); // 密送人
}
// 设置邮件消息的主题
mailMessage.setSubject(mailInfo.getSubject());
// 设置邮件消息发送的时间
mailMessage.setSentDate(new Date());
// 设置邮件消息的主要内容
mailMessage.setText(mailInfo.getContent());
// MiniMultipart类是一个容器类,包含MimeBodyPart类型的对象
Multipart multipart = new MimeMultipart();
// 创建一个包含HTML内容的MimeBodyPart
BodyPart messageBodyPart = new MimeBodyPart();
// 显示以html格式的文本内容
messageBodyPart.setContent(mailInfo.getContent(), "text/html;charset=gbk");
multipart.addBodyPart(messageBodyPart);
// 2.保存多个附件
if (mailInfo.getAttachFileNames() != null) {
addTach(mailInfo.getAttachFileNames(), multipart);
}
mailMessage.setContent(multipart);
// 发送邮件
Transport.send(mailMessage, mailMessage.getAllRecipients());
return true;
} catch (MessagingException ex) {
ex.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return false;
}


// 添加多个附件
public void addTach(String fileList[], Multipart multipart)
throws MessagingException, UnsupportedEncodingException {
for (int index = 0; index < fileList.length; index++) {
MimeBodyPart mailArchieve = new MimeBodyPart();
FileDataSource fds = new FileDataSource(fileList[index]);
mailArchieve.setDataHandler(new DataHandler(fds));
mailArchieve.setFileName(MimeUtility.encodeText(fds.getName(), "GBK", "B"));
multipart.addBodyPart(mailArchieve);
}
}


private String getMailList(String[] mailArray) {


StringBuffer toList = new StringBuffer();
int length = mailArray.length;
if (mailArray != null && length < 2) {
toList.append(mailArray[0]);
} else {
for (int i = 0; i < length; i++) {
toList.append(mailArray[i]);
if (i != (length - 1)) {
toList.append(",");
}


}
}
return toList.toString();


}


/**

* @param mailServerHost
*            邮件服务器域名
* @param mailServerPort
*            邮件服务器地址
* @param userName
*            用户名
* @param password
*            密码
* @param toAddress
*            邮件发送地址
* @param subject
*            邮件主题
* @param content
*            邮件内容
*/
public EmailUtil(String mailServerHost, String mailServerPort, String userName, String password, String[] toAddress,
String[] csAddress, String msAddress[], String subject, String content, String[] attachments) {
this.mailInfo.setMailServerHost(mailServerHost);
this.mailInfo.setMailServerPort(mailServerPort);
this.mailInfo.setValidate(true);
this.mailInfo.setUserName(userName);
this.mailInfo.setPassword(password);
this.mailInfo.setFromAddress(userName);
this.mailInfo.setToAddress(toAddress);
this.mailInfo.setCsAddress(csAddress);
this.mailInfo.setMsAddress(msAddress);
this.mailInfo.setSubject(subject);
this.mailInfo.setContent(content);
this.mailInfo.setAttachFileNames(attachments);
}


private MailSenderInfo mailInfo = new MailSenderInfo();


public MailSenderInfo getMailInfo() {
return mailInfo;
}


public void setMailInfo(MailSenderInfo mailInfo) {
this.mailInfo = mailInfo;
}


public boolean isEmail(final String searchPhrase) {
final String check = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
final Pattern regex = Pattern.compile(check);
final Matcher matcher = regex.matcher(searchPhrase);
return matcher.matches();
}


public static String getVerifyMail(String userId, String email, String verifyCode) {


String content = "<div class=\"main_cen\">\n\n" + "<p class=\"title_all  zi_6\">\n" + "感谢您注册会员!<br>\n"
+ "您的登陆账号为:<span class=\"title_big2\"><a target=\"_blank\" href=\"mailto:" + email + "\">" + email
+ "</a> </span>\n" + "</p>\n\n" +


" <p class=\"title_all_top zi_6 link\">\n" + "要启用帐户并确认电子邮件地址,请单击以下链接: <br>\n\n" +


"<a target=\"_blank\" href=\"http://www.uxiaoqu.com/register/signup.action?v=" + verifyCode + "&userID="
+ userId + "\">http://www.uxiaoqu.com/register/signup.action?v=" + verifyCode + "&userID=" + userId
+ "</a><br>\n" + "<span class=\"red\">(请在48小时内完成确认,48小时后邮件失效,您将需要重新填写注册信息) </span>\n" + "</p>\n\n" +


"<p class=\"title_all_top zi_6\">" + "如果通过点击以上链接无法访问,请将该网址复制并粘贴至新的浏览器窗口中。<br> \n"
+ "如果您错误地收到了此电子邮件,您无需执行任何操作来取消帐户!此帐户将不会启动。\n" + "</p>\n\n"
// +
// "<p class=\"title_all_top zi_6 link\">\n\n"
// +


// "如果您对您的帐户有任何问题或疑问,请浏览新浪会员注册常见问题解答,地址如下:<br>\n"
// +
// "<a target=\"_blank\"
// href=\"http://iask.sina.com.cn/browse/get_class4.php?fatherid=1315&amp;nav=1\">http://iask.sina.com.cn/browse/get_class4.php?fatherid=1315&amp;nav=1
// </a><br>"
+ "这只是一封公告邮件。我们并不监控或回答对此邮件的回复。\n" + "</p>\n\n" +


"</div>\n";


return content;
}


public static void main(String[] args) {
// String mailServerHost = "smtp.exmail.qq.com";
// String mailServerPort = "25";
// String userName = "service@raylinetech.com";
// String password = "WLlrXJC83";
// String[] toAddress = { "274047154@qq.com" };
// String cs[] = { "15522500416@163.com" };
// String ms[] = null;
String subject = "难道里?";
// String[] arrArchievList = null;
//
String content = "信。<a href=\"http://login.sina.com.cn/signup/signupmail2.php?r=d8d75c579625472cf70196914e7fbebd\">http://login.sina.com.cn/signup/signupmail2.php?r=d8d75c579625472cf70196914e7fbebd</a>";
// EmailUtil util = new EmailUtil(mailServerHost, mailServerPort,
// userName, password, toAddress, cs, ms, subject,
// content, arrArchievList);
// System.out.println(util.sendMail());
// // System.out.println(EmailUtil.getVerifyMail("123", "1234"));


EmailUtil.sendEmail("18902022392@163.com", "15522500416@163.com", null, subject, content);


}


public static Boolean sendEmail(String toAddress, String cs, String ms, String subject, String content) {
Boolean flag = false;


// String mailServerHost = "smtp.exmail.qq.com";
// String mailServerPort = "25";
// String userName = "service@raylinetech.com";
// String password = "WLlrXJC83";
String mailServerHost = Global.getConfig("mailServerHost");
String mailServerPort = Global.getConfig("mailServerPart");
;
String userName = Global.getConfig("userName");
String password = Global.getConfig("password");
String[] toAddressArr = toAddress.split(",");
String csArr[] = cs.split(",");
String msArr[] = org.apache.commons.lang3.StringUtils.isNotBlank(ms) ? ms.split(",") : null;
String[] arrArchievList = null;


EmailUtil util = new EmailUtil(mailServerHost, mailServerPort, userName, password, toAddressArr, csArr, msArr,
subject, content, arrArchievList);
flag = util.sendMail();
System.out.println(flag);
return flag;
}


}


class MailSenderInfo {
// IP and port of server which send mail
private String mailServerHost;
private String mailServerPort = "";
// address of server which send mail
private String fromAddress;
// address of server which receive mail
private String[] toAddress;
// address of server which receive mail
private String[] csAddress;
// address of server which receive mail
private String[] msAddress;
// user name and password of server which will login and send mail
private String userName;
private String password;
// if need authentication
private boolean validate = false;
// theme of mail
private String subject;
// context of mail
private String content;
// file name of attachment in email
private String[] attachFileNames;


/**
* get properties of mail conversation
*/
public Properties getProperties() {
Properties p = new Properties();
p.put("mail.smtp.host", this.mailServerHost);
p.put("mail.smtp.port", this.mailServerPort);
p.put("mail.smtp.auth", validate ? "true" : "false");
return p;
}


public String getMailServerHost() {
return mailServerHost;
}


public void setMailServerHost(String mailServerHost) {
this.mailServerHost = mailServerHost;
}


public String getMailServerPort() {
return mailServerPort;
}


public void setMailServerPort(String mailServerPort) {
this.mailServerPort = mailServerPort;
}


public boolean isValidate() {
return validate;
}


public void setValidate(boolean validate) {
this.validate = validate;
}


public String[] getAttachFileNames() {
return attachFileNames;
}


public void setAttachFileNames(String[] fileNames) {
this.attachFileNames = fileNames;
}


public String getFromAddress() {
return fromAddress;
}


public void setFromAddress(String fromAddress) {
this.fromAddress = fromAddress;
}


public String getPassword() {
return password;
}


public void setPassword(String password) {
this.password = password;
}


public String[] getToAddress() {
return toAddress;
}


public void setToAddress(String[] toAddress) {
this.toAddress = toAddress;
}


public String[] getCsAddress() {
return csAddress;
}


public void setCsAddress(String[] csAddress) {
this.csAddress = csAddress;
}


public String[] getMsAddress() {
return msAddress;
}


public void setMsAddress(String[] msAddress) {
this.msAddress = msAddress;
}


public String getUserName() {
return userName;
}


public void setUserName(String userName) {
this.userName = userName;
}


public String getSubject() {
return subject;
}


public void setSubject(String subject) {
this.subject = subject;
}


public String getContent() {
return content;
}


public void setContent(String textContent) {
this.content = textContent;
}
}


class MyAuthenticator extends Authenticator {
String userName = null;
String password = null;


public MyAuthenticator() {
}


public MyAuthenticator(String username, String password) {
this.userName = username;
this.password = password;
}


protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, password);
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值