邮件的相关内容实体类
package com.tydic.web.cust.common;
public class MailMessage {
/**
* 邮件的主题
*/
private String subject;
/**
* 邮件发送方
*/
private String from;
/**
* 邮件接收方
*/
private String[] tos;
private String[] ccs;
private String[] bccs;
/**
* 邮件内容
*/
private String content;
/**
* 邮件附件
*/
private String[] fileNames;
/**
* No parameter constructor.
*/
public MailMessage(){}
/**
* Construct a MailMessage object.
*/
public MailMessage(String subject, String from, String[] tos,
String[] ccs, String[] bccs, String content, String[] fileNames) {
this.subject = subject;
this.from = from;
this.tos = tos;
this.ccs = ccs;
this.bccs = bccs;
this.content = content;
this.fileNames = fileNames;
}
/**
* Construct a simple MailMessage object.
*/
public MailMessage(String subject, String from, String to, String content) {
this.subject = subject;
this.from = from;
this.tos = new String[]{to};
this.content = content;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
public String[] getTos() {
return tos;
}
public void setTos(String[] tos) {
this.tos = tos;
}
public String[] getCcs() {
return ccs;
}
public void setCcs(String[] ccs) {
this.ccs = ccs;
}
public String[] getBccs() {
return bccs;
}
public void setBccs(String[] bccs) {
this.bccs = bccs;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String[] getFileNames() {
return fileNames;
}
public void setFileNames(String[] fileNames) {
this.fileNames = fileNames;
}
}
调用邮发送
package com.tydic.web.cust.common;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.ResourceBundle;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.NoSuchProviderException;
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 javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
public class MsgSendUtil {
private static final Logger LOGGER = Logger.getLogger(MsgSendUtil.class);
private static Properties properties = new Properties();
private static String propertyName = "mail_msg.properties";
public final static String FILE_SEP = System.getProperty("file.separator");//文件分隔符(在 UNIX 系统中是“/”)
private static String SMTPServer;
private static String SMTPUsername;
private static String SMTPPassword;
private static String POP3Server;
private static String POP3Username;
private static String POP3Password;
static {
loadConfigProperties();
}
public static void main(String[] args) {
String[] tos = {"xxxxx@qq.com","xxxx@xxx.com"};
Map<String,Object> map = new HashMap<String, Object>();
ReadProperties r = new ReadProperties();
map = r.loadToMap("src/main/resources/mail_msg.properties");
String username = map.get("AbcCommon.mail.SMTPUsername").toString();
System.out.println(StringUtils.join(tos, ","));
//发送邮件
MailMessage mail = new MailMessage(
"test-subject",
username,
"xxxx@qq.com",
"这是一封测试邮件,请查收");
//设置附件
mail.setTos(tos);
sendEmail(mail);
}
public static String getPropertyPath(){
String path = System.getProperty("user.dir")+FILE_SEP+"config"+FILE_SEP+propertyName;
LOGGER.info(path);
return propertyName;
}
/**
* Load configuration properties to initialize attributes.
* @throws Exception
*/
private static void loadConfigProperties() {
try {
Properties prop = new Properties();
InputStream inStream = MsgSendUtil.class.getClassLoader().getResourceAsStream(getPropertyPath());//包内配置文件
prop.load(inStream);
SMTPServer = prop.getProperty("AbcCommon.mail.SMTPServer");
SMTPUsername = prop.getProperty("AbcCommon.mail.SMTPUsername");
SMTPPassword = prop.getProperty("AbcCommon.mail.SMTPPassword");
POP3Server = prop.getProperty("AbcCommon.mail.POP3Server");
POP3Username = prop.getProperty("AbcCommon.mail.POP3Username");
POP3Password = prop.getProperty("AbcCommon.mail.POP3Password");
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Send email. Note that the fileNames of MailMessage are the absolute path of file.
* @param mail The MailMessage object which contains at least all the required
* attributes to be sent.
*/
public static void sendEmail(MailMessage mail) {
sendEmail(null, mail, false);
}
/**
* 发送匿名电子邮件 请注意,尽管我们可以从地址中提供任何地址,
*(例如:<b>'a@a.a'有效</ b>),MailMessage应该永远是
* 电子邮件地址格式正确(例如<b>'aaaa'无效</ b>)。 除此以外
* 会抛出异常,表示用户名无效。
* @param邮件MailMessage对象至少包含所有必需的
* 要发送的属性。
*/
public static void sendAnonymousEmail(MailMessage mail) {
String dns = "dns://";
Hashtable<String, String> env = new Hashtable<String, String>();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.dns.DnsContextFactory");
env.put(Context.PROVIDER_URL, dns);
String[] tos = mail.getTos();
try {
DirContext ctx = new InitialDirContext(env);
for(String to:tos) {
String domain = to.substring(to.indexOf('@') + 1);
//Get MX(Mail eXchange) records from DNS
Attributes attrs = ctx.getAttributes(domain, new String[] { "MX" });
if (attrs == null || attrs.size() <= 0) {
throw new java.lang.IllegalStateException(
"Error: Your DNS server has no Mail eXchange records!");
}
@SuppressWarnings("rawtypes")
NamingEnumeration servers = attrs.getAll();
String smtpHost = null;
boolean isSend = false;
StringBuffer buf = new StringBuffer();
//try all the mail exchange server to send the email.
while (servers.hasMore()) {
Attribute hosts = (Attribute) servers.next();
for (int i = 0; i < hosts.size(); ++i) {
//sample: 20 mx2.qq.com
smtpHost = (String) hosts.get(i);
//parse the string to get smtpHost. sample: mx2.qq.com
smtpHost = smtpHost.substring(smtpHost.lastIndexOf(' ') + 1);
try {
sendEmail(smtpHost, mail, true);
isSend = true;
return;
} catch (Exception e) {
LOGGER.error("", e);
buf.append(e.toString()).append("\r\n");
continue;
}
}
}
if (!isSend) {
throw new java.lang.IllegalStateException("Error: Send email error."
+ buf.toString());
}
}
} catch (NamingException e) {
LOGGER.error("", e);
}
}
/**
* 发电子邮件。 使用字符串数组表示附件文件名。
* @see #sendEmail(String, String, String[], String[], String[], String, File[])
*/
private static void sendEmail(String smtpHost,
MailMessage mail, boolean isAnonymousEmail) {
if(mail == null) {
throw new IllegalArgumentException("Param mail can not be null.");
}
String[] fileNames = mail.getFileNames();
//only needs to check the param: fileNames, other params would be checked through
//the override method.
File[] files = null;
if(fileNames != null && fileNames.length > 0) {
files = new File[fileNames.length];
for(int i = 0; i < files.length; i++) {
File file = new File(fileNames[i]);
files[i] = file;
}
}
sendEmail(smtpHost, mail.getSubject(), mail.getFrom(), mail.getTos(),
mail.getCcs(), mail.getBccs(), mail.getContent(), files, isAnonymousEmail);
}
/**
* 发电子邮件。 请注意,内容和附件不能同时为空。
* @param smtpHost SMTPHost。 发送匿名电子邮件时需要此参数。
*发送普通电子邮件时,param被忽略,默认的SMTPServer
*配置使用。
* @param subject电子邮件主题。
* @param来自发件人地址。 该地址必须在SMTPServer中可用。
* @param tos接收者地址。 至少1个地址有效。
* @param ccs'复制'接收器。 可以是空的
* @param bccs'encrypt copy'接收器。 可以是空的
* @param内容电子邮件内容。
* @param附件文件数组表示要发送的附件。
* @param isAnonymousEmail如果此邮件以匿名模式发送。 当设置为true时,
* param smtpHost是必需的,发件人的电子邮件地址应该是正确的
*模式。
*/
private static void sendEmail(String smtpHost, String subject,
String from, String[] tos, String[] ccs, String[] bccs,
String content, File[] attachments, boolean isAnonymousEmail) {
//parameter check
if(isAnonymousEmail && smtpHost == null) {
throw new IllegalStateException(
"发送匿名电子邮件时,param smtpHost不能为空");
}
if(subject == null || subject.length() == 0) {
subject = "主题自动生成";
}
if(from == null) {
throw new IllegalArgumentException("发件人的地址是必填的.");
}
if(tos == null || tos.length == 0) {
throw new IllegalArgumentException(
"至少需要1个接收地址.");
}
if(content == null && (attachments == null || attachments.length == 0)) {
throw new IllegalArgumentException(
"内容和附件不能同时为空");
}
if(attachments != null && attachments.length > 0) {
List<File> invalidAttachments = new ArrayList<>();
for(File attachment:attachments) {
if(!attachment.exists() || attachment.isDirectory()
|| !attachment.canRead()) {
invalidAttachments.add(attachment);
}
}
if(invalidAttachments.size() > 0) {
String msg = "";
for(File attachment:invalidAttachments) {
msg += "\n\t" + attachment.getAbsolutePath();
}
throw new IllegalArgumentException(
"以下附件无效:" + msg);
}
}
Session session;
Properties props = new Properties();
props.put("mail.transport.protocol", "smtp");
if(isAnonymousEmail) {
//only anonymous email needs param smtpHost
props.put("mail.smtp.host", smtpHost);
props.put("mail.smtp.auth", "false");
session = Session.getInstance(props, null);
} else {
//normal email does not need param smtpHost and uses the default host SMTPServer
props.put("mail.smtp.host", SMTPServer);
props.put("mail.smtp.auth", "true");
session = Session.getInstance(props,
new MailAuthenticator(SMTPUsername, SMTPPassword));
}
//create message
MimeMessage msg = new MimeMessage(session);
try {
//Multipart is used to store many BodyPart objects.
Multipart multipart=new MimeMultipart();
BodyPart part = new MimeBodyPart();
part.setContent(content,"text/html;charset=gb2312");
//add email content part.
multipart.addBodyPart(part);
//add attachment parts.
if(attachments != null && attachments.length > 0) {
for(File attachment: attachments) {
String fileName = attachment.getName();
DataSource dataSource = new FileDataSource(attachment);
DataHandler dataHandler = new DataHandler(dataSource);
part = new MimeBodyPart();
part.setDataHandler(dataHandler);
//solve encoding problem of attachments file name.
try {
fileName = MimeUtility.encodeText(fileName);
} catch (UnsupportedEncodingException e) {
LOGGER.error(
"Cannot convert the encoding of attachments file name.", e);
}
//set attachments the original file name. if not set,
//an auto-generated name would be used.
part.setFileName(fileName);
multipart.addBodyPart(part);
}
}
msg.setSubject(subject);
msg.setSentDate(new Date());
//set sender
msg.setFrom(new InternetAddress(from));
//set receiver,
for(String to: tos) {
msg.addRecipient(RecipientType.TO, new InternetAddress(to));
}
if(ccs != null && ccs.length > 0) {
for(String cc: ccs) {
msg.addRecipient(RecipientType.CC, new InternetAddress(cc));
}
}
if(bccs != null && bccs.length > 0) {
for(String bcc: bccs) {
msg.addRecipient(RecipientType.BCC, new InternetAddress(bcc));
}
}
msg.setContent(multipart);
//save the changes of email first.
msg.saveChanges();
//to see what commands are used when sending a email, use session.setDebug(true)
//session.setDebug(true);
//send email
Transport.send(msg);
LOGGER.info("+++++++++++++++++++++++++发送电子邮件成功+++++++++++++++++++++++");
} catch (NoSuchProviderException e) {
LOGGER.error("电子邮件提供程序配置错误.", e);
} catch (MessagingException e) {
LOGGER.error("发送电子邮件错误.", e);
}
}
}