resource.properties
郵件配置屬性
email.server.issend=true
email.server.transport=smtp
email.server.host=smtp.gmail.com
[email protected]
[email protected]
email.from.userPassword=36989688
email.server.port=465
java 發送email 方法
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLDecoder;
import java.security.Security;
import java.util.Date;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
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.util.ByteArrayDataSource;
private void mailSendProccess(EmailSenderInfo mailSenderInfo,
String contextPath) throws IOException {
// 獲取郵件配置信息
InputStream inputStream = new BufferedInputStream(
new FileInputStream("/"+this.getWebInfPath()
+ "/WEB-INF/resource.properties"));
perties.load(inputStream);
// 注意: linux 環境下 要加上一個根盤符,要不然 路徑不識別
logger.info("....郵件配置屬性文件路徑...:"+"/"+this.getWebInfPath()+"/WEB-INF/resource.properties");
mailSenderInfo.setMailServerHost(perties.getProperty("email.server.host"));
mailSenderInfo.setTransport(perties.getProperty("email.server.transport"));
mailSenderInfo.setFromAddress(perties.getProperty("email.from.address"));
mailSenderInfo.setUserName(perties.getProperty("email.from.userName"));
mailSenderInfo.setPassword(perties.getProperty("email.from.userPassword"));
mailSenderInfo.setMailServerPort(perties.getProperty("email.server.port"));
logger.info("==== com.m3td.m3ssi.bussion.email.MailSendCustomerManagerImpl.mailSendProccess() start====");
try {
// 設置郵件服務屬性
Properties props = new Properties();
logger.info("......Gmail郵件屬性配置 start.....");
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
props.setProperty("mail.smtp.host", mailSenderInfo.getMailServerHost());
props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
props.setProperty("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.smtp.port", mailSenderInfo.getMailServerPort());
props.setProperty("mail.smtp.socketFactory.port", mailSenderInfo.getMailServerPort());
props.setProperty("mail.smtp.auth", "true");
final String username =mailSenderInfo.getUserName() ;
final String password = mailSenderInfo.getPassword();
// 根據屬性新建一個郵件會話,消息對象 重要: gmail 必須要安全認證,網易和qq 的不需要
Session session = Session.getDefaultInstance(props, new Authenticator(){
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}});
logger.info("......Gmail賬號認證成功.....");
session.setDebug(true);
MimeMessage message = new MimeMessage(session);
message.setSubject(mailSenderInfo.getSubject()); // 設置主題
message.setSentDate(new Date()); // 設置發信時間
message.setFrom(new InternetAddress(mailSenderInfo
.getFromAddress()));// 設置發件人地址
logger.info("mailSenderInfo.getFromAddress()"+mailSenderInfo.getFromAddress());
message.setContent(contextPath,"text/calendar;method=REQUEST;charset=UTF-8");
// 添加收件人地址
String[] mailToArray = mailSenderInfo.getToAddressArray();
if (mailToArray == null || mailToArray.length == 0) {
InternetAddress toAddress = new InternetAddress(mailSenderInfo
.getToAddress());
message.setRecipient(Message.RecipientType.TO, toAddress);
} else {
InternetAddress[] toAddressList = new InternetAddress[mailToArray.length];
for (int index = 0; index < mailToArray.length; index++) {
if (toAddressList != null && mailToArray[index] != null
&& (mailToArray[index].trim().length() > 0)) {
toAddressList[index] = new InternetAddress(
mailToArray[index]);
}
}
message.addRecipients(Message.RecipientType.TO, toAddressList);
logger.info("發件人地址:"+toAddressList.toString());
}
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setDataHandler(new DataHandler(
new ByteArrayDataSource(contextPath.toString(),
"text/calendar;method=REQUEST;charset=\"UTF-8\"")));
// 設置正文
Multipart container = new MimeMultipart();
container.addBodyPart(messageBodyPart);
// 設置附件信息
MimeBodyPart fileBodyPart = null;
FileDataSource dataSource = null;
String[] fileNams = mailSenderInfo.getAttachFileNames();
if (fileNams != null && fileNams.length > 0) {
for (int index = 0; index < fileNams.length; index++) {
if (fileNams[index] != null
&& fileNams[index].trim().length() > 0) {
fileBodyPart = new MimeBodyPart();
dataSource = new FileDataSource(fileNams[index]);// 要發送的附件地址
fileBodyPart
.setDataHandler(new DataHandler(dataSource));
fileBodyPart.setFileName(dataSource.getName());// 設置附件的名稱
container.addBodyPart(fileBodyPart);
}
}
message.setContent(container);// 設置附件內容
}
message.saveChanges();// 存儲郵件信息
Transport tranSport = session.getTransport(mailSenderInfo
.getTransport());
tranSport.connect(mailSenderInfo.getMailServerHost(),
mailSenderInfo.getUserName(), mailSenderInfo.getPassword());
logger.info("mailSenderInfo.getMailServerHost():"+mailSenderInfo.getMailServerHost());
tranSport.sendMessage(message, message.getAllRecipients()); // 發送郵件
tranSport.close();
logger.info("........郵件發送成功....");
} catch (MessagingException e) {
logger.error("==== com.m3td.m3ssi.bussion.email.MailSendCustomerManagerImpl.mailSendProccess(MailSenderInfo mailSenderInfo)"
+ " 郵件發送失敗:" + e.getMessage());
}
logger.info("==== com.m3td.m3ssi.bussion.email.MailSendCustomerManagerImpl.mailSendProccess() end====");
}
// 處理普通java類讀取web-inf 下的文件路徑問題
private String getWebInfPath() {
URL url = getClass().getProtectionDomain().getCodeSource()
.getLocation();
String path = url.toString();
int index = path.indexOf("WEB-INF");
if (index == -1) {
index = path.indexOf("classes");
}
if (index == -1) {
index = path.indexOf("bin");
}
path = path.substring(0, index);
if (path.startsWith("zip")) {// 當class文件在war中時,此時返回zip:D:/...這樣的路徑
path = path.substring(4);
} else if (path.startsWith("file")) {// 當class文件在class文件中時,此時返回file:/D:/...這樣的路徑
path = path.substring(6);
} else if (path.startsWith("jar")) {// 當class文件在jar文件裏面時,此時返回jar:file:/D:/...這樣的路徑
path = path.substring(10);
}
try {
path = URLDecoder.decode(path, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return path;
}