javamail 发送gmail 邮件 例子

来源:互联网 发布:lr软件怎么下载 编辑:程序博客网 时间:2024/05/16 01:41

resource.properties


邮件配置属性

email.server.issend=true
email.server.transport=smtp
email.server.host=smtp.gmail.com
email.from.address=xxx@gmail.com
email.from.userName=xxx@gmail.com
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;
}





原创粉丝点击