你的位置:首页 > Java教程

[Java教程]java 使用maven发送邮件

1.pom.

<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;
}


}