java的郵箱發送工具類

來源:互聯網
上載者:User
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);
}
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.