1. 程式人生 > >java使用javamail傳送郵件

java使用javamail傳送郵件

1.pom.xml檔案配置

<dependency>
    <groupId>javax.mail</groupId>
    <artifactId>mail</artifactId>
    <version>1.4.7</version>
</dependency>

 

2.實現

/**
* 
*/
package com.cmsz.rc.services.impl;
import java.io.File;
import java.util.List;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import com.cmsz.rc.constant.EmailConfig;
import com.cmsz.rc.exception.ServiceLevelException;
import com.cmsz.rc.model.EmailNoticeInfoModel;
import com.cmsz.rc.services.EmailNoticeService;
import com.cmsz.rc.verification.MailAuthenticator;
/**
* @author 
*
*/
@Service("EmailNoticeService")
public class EmailNoticeServiceImpl implements EmailNoticeService {
/**
* 異常日誌記錄
*/
private static final Logger LOGGER = LoggerFactory.getLogger(EmailNoticeServiceImpl.class);
/**
* @field props Properties
* 
* @description Properties配置檔案
*/
private final Properties props = System.getProperties();
/**
* @field authenticator MailAuthenticator
* 郵件伺服器登陸認證
*/
private MailAuthenticator authenticator;
/**
* @field session Session
* 
* @Description: 郵箱session
*/
private Session session;

private EmailNoticeServiceImpl(){

}
/**
* 建立一個新的例項 MailSender.
*
* @param smtpHostName SMTP郵件伺服器地址
* @param username 傳送人的使用者名稱
* @param password 傳送郵件的密碼
*/
public EmailNoticeServiceImpl(final String smtpHostName, final String username,
final String password) {
init(username, password, smtpHostName);
}
/**
* 建立一個新的例項 MailSender.
*
* @param username 傳送郵件的使用者名稱(地址),並以此解析SMTP伺服器地址
* @param password 傳送郵件的密碼
*/
public EmailNoticeServiceImpl(final String username, final String password) {
final String smtpHostName = "smtp." + username.split("@")[1];
init(username, password, smtpHostName);
}
/**
* init
* 
* @Description 初始化
* @param username 傳送郵件的使用者名稱(地址)
* @param password 密碼
* @param smtpHostName SMTP主機地址
* @return void
*/
private void init(String username, String password, String smtpHostName) {
// 初始化props
props.put("mail.debug", "true");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.host", smtpHostName);
// props.put("mail.smtp.auth.mechanisms", "NTLM");
authenticator = new MailAuthenticator(username, password);
session = Session.getInstance(props, authenticator);
}
/**
* send
* 
* @Description 傳送郵件
* @param recipient 收件人郵箱地址
* @param subject 郵件主題
* @param content 郵件內容
* @throws AddressException
* @throws MessagingException
* @return void
*/
public void send(String recipient, String subject, EmailNoticeInfoModel emailNoticeInfoModel)
throws AddressException, MessagingException {
LOGGER.info("recipient:"+recipient);
LOGGER.info("subject:"+subject);
LOGGER.info("getContent:"+emailNoticeInfoModel.getContent());
System.out.println("recipient:"+recipient);
System.out.println("subject:"+subject);
System.out.println("getContent:"+emailNoticeInfoModel.getContent());
this.init(EmailConfig.getUsername(), EmailConfig.getPassword(), EmailConfig.getSmtphostname());

//Authenticator auth = new GUIAuthenticator();
props.setProperty("mail.transport.protocol", "smtp"); 
props.setProperty("mail.smtp.auth", "true");
// 通過傳入的引數獲得Authenticator子類物件

// Session session = Session.getInstance(props, auth); 
// session.setDebug(true); 
// 建立mime型別郵件
final MimeMessage message = new MimeMessage(session);
// 設定發信人
message.setFrom(new InternetAddress(authenticator.getUsername()));
// 設定收件人
message.setRecipient(RecipientType.TO, new InternetAddress(recipient));
// 設定主題
message.setSubject(subject);
// 設定郵件內容
message.setContent(emailNoticeInfoModel.getContent(), "text/html;charset=utf-8");
// 傳送
Transport.send(message);
//EmailNoticeInfoModel emailNoticeInfoModel=new EmailNoticeInfoModel();
//emailNoticeInfoModel.setId(BigInteger.valueOf(1l));

// System.out.println(emailNoticeDao.getEmailNoticeInfoById(emailNoticeInfoModel).getBusiness_lines());

}
/**
* send
* 
* @Description 群發郵件
* @param recipients 收件人們
* @param subject 主題
* @param content 內容
* @throws AddressException
* @throws MessagingException
* @return void
*/
public void send(List<String> recipients, String subject, EmailNoticeInfoModel emailNoticeInfoModel)
throws AddressException, MessagingException {
this.init(EmailConfig.getUsername(), EmailConfig.getPassword(), EmailConfig.getSmtphostname());
final MimeMessage message = new MimeMessage(session);
System.out.println(authenticator.getUsername());
message.setFrom(new InternetAddress(authenticator.getUsername()));
// 設定收件人們
final int num = recipients.size();
InternetAddress[] addresses = new InternetAddress[num];
for (int i = 0; i < num; i++) {
addresses[i] = new InternetAddress(recipients.get(i));
}
message.setRecipients(RecipientType.TO, addresses);
// 設定主題
message.setSubject(subject);
// 設定郵件內容
message.setContent(emailNoticeInfoModel.getContent(), "text/html;charset=utf-8");
// 傳送
Transport.send(message);
}
/**
* 
* send 郵件傳送單發(帶附件)
* @Title: send
* @Description: 傳送
* @param @param recipient
* @param @param subject
* @param @param content
* @param @param file
* @param @throws AddressException
* @param @throws MessagingException 設定檔案
* @return void 返回型別
* @throws
*/
@Override
public void send(String recipient, String subject, EmailNoticeInfoModel emailNoticeInfoModel, File file)throws ServiceLevelException {
// 建立mime型別郵件
final MimeMessage message = new MimeMessage(session);
try{
// 設定發信人
message.setFrom(new InternetAddress(authenticator.getUsername()));
// 設定收件人
message.setRecipient(RecipientType.TO, new InternetAddress(recipient));
// 設定主題
message.setSubject(subject);
// 向multipart物件中新增郵件的各個部分內容,包括文字內容和附件
Multipart multipart = new MimeMultipart();
// 新增郵件正文
BodyPart contentPart = new MimeBodyPart();
contentPart.setContent(emailNoticeInfoModel.toString(), "text/html;charset=UTF-8");
multipart.addBodyPart(contentPart);
// 新增附件的內容
if (file != null) {
BodyPart attachmentBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(file);
attachmentBodyPart.setDataHandler(new DataHandler(source));
// 網上流傳的解決檔名亂碼的方法,其實用MimeUtility.encodeWord就可以很方便的搞定
// 這裡很重要,通過下面的Base64編碼的轉換可以保證你的中文附件標題名在傳送時不會變成亂碼
//sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();
//messageBodyPart.setFileName("=?GBK?B?" + enc.encode(file.getName().getBytes()) + "?=");
//MimeUtility.encodeWord可以避免檔名亂碼
attachmentBodyPart.setFileName(MimeUtility.encodeWord(file.getName()));
multipart.addBodyPart(attachmentBodyPart);
}
// 將multipart物件放到message中
message.setContent(multipart);
// 儲存郵件
message.saveChanges();
// 傳送
Transport.send(message);
}catch(Exception e){
LOGGER.error("郵件傳送異常:{}",e);
throw new ServiceLevelException(e);
}

}
/**
* 
* send 郵件傳送群發(帶附件)
* @Title: send
* @Description: 傳送
* @param @param recipients
* @param @param subject
* @param @param content
* @param @param file
* @param @throws AddressException
* @param @throws MessagingException 設定檔案
* @return void 返回型別
* @throws
*/
@Override
public void send(List<String> recipients, String subject,EmailNoticeInfoModel emailNoticeInfoModel, File file) throws ServiceLevelException {
final MimeMessage message = new MimeMessage(session);
try{
message.setFrom(new InternetAddress(authenticator.getUsername()));
// 設定收件人們
final int num = recipients.size();
InternetAddress[] addresses = new InternetAddress[num];
for (int i = 0; i < num; i++) {
addresses[i] = new InternetAddress(recipients.get(i));
}
message.setRecipients(RecipientType.TO, addresses);
// 設定主題
message.setSubject(subject);
// 向multipart物件中新增郵件的各個部分內容,包括文字內容和附件
Multipart multipart = new MimeMultipart();
// 新增郵件正文
BodyPart contentPart = new MimeBodyPart();
contentPart.setContent(emailNoticeInfoModel.toString(), "text/html;charset=UTF-8");
multipart.addBodyPart(contentPart);
// 新增附件的內容
if (file != null) {
BodyPart attachmentBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(file);
attachmentBodyPart.setDataHandler(new DataHandler(source));
// 網上流傳的解決檔名亂碼的方法,其實用MimeUtility.encodeWord就可以很方便的搞定
// 這裡很重要,通過下面的Base64編碼的轉換可以保證你的中文附件標題名在傳送時不會變成亂碼
//sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();
//messageBodyPart.setFileName("=?GBK?B?" + enc.encode(file.getName().getBytes()) + "?=");
//MimeUtility.encodeWord可以避免檔名亂碼
attachmentBodyPart.setFileName(MimeUtility.encodeWord(file.getName()));
multipart.addBodyPart(attachmentBodyPart);
}
// 將multipart物件放到message中
message.setContent(multipart);
// 儲存郵件
message.saveChanges();
// 傳送
Transport.send(message);
}catch(Exception e){
LOGGER.error("郵件傳送異常:{}",e);
throw new ServiceLevelException(e);
}
}

/**
* 
* send 郵件傳送群發
* @Title: send
* @Description: 傳送
* @param recipients 傳送
* @param duplicateSends 抄送
* @param subject
* @param content
* @param file
* @throws AddressException
* @throws MessagingException 設定檔案
* @return void 返回型別
* @throws
*/
@Override
public void send(List<String> recipients, List<String> duplicateSends, String subject,
EmailNoticeInfoModel emailNoticeInfoModel)
throws AddressException, MessagingException {
this.init(EmailConfig.getUsername(), EmailConfig.getPassword(), EmailConfig.getSmtphostname());
final MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(authenticator.getUsername()));
if(recipients!=null){
// 設定收件人們
final int num = recipients.size();
InternetAddress[] addresses = new InternetAddress[num];
for (int i = 0; i < num; i++) {
addresses[i] = new InternetAddress(recipients.get(i));
}
message.setRecipients(RecipientType.TO, addresses);
}
if(duplicateSends.size()>0){
// 設定抄送人們
final int duplicateSendNum = duplicateSends.size();
InternetAddress[] duplicateSendAddresses = new InternetAddress[duplicateSendNum];
for (int i = 0; i < duplicateSendNum; i++) {
duplicateSendAddresses[i] = new InternetAddress(duplicateSends.get(i));
}
message.setRecipients(RecipientType.CC, duplicateSendAddresses); // 抄送人 
}
// 設定主題
message.setSubject(subject);
// 設定郵件內容
message.setContent(emailNoticeInfoModel.getContent(), "text/html;charset=utf-8");
// 傳送
Transport.send(message);
//Transport tran = session.getTransport("smtp"); 
//tran.sendMessage(message, message.getAllRecipients()); 
}
}

郵件認證類

package com.cmsz.rc.constant;
public class EmailConfig {
public EmailConfig(){

}


private static final String SMTPHOSTNAME="郵件伺服器地址"; 
private static final String USERNAME = "使用者名稱"; 
private static final String PASSWORD="密碼";
public static String getSmtphostname() {
return SMTPHOSTNAME;
}
public static String getUsername() {
return USERNAME;
}
public static String getPassword() {
return PASSWORD;
}

}