public class MailInfo {
/** 发送邮件的服务器的IP */
private String mailHost;
/** 发送邮件的服务器的端口 */
private String mailPort;
/** 发送邮件的用户名(邮箱全名称) */
private String username;
/** 发送邮件的密码 */
private String password;
/** 错误信息发送地址(多个邮件地址以";"分隔) */
private String errorTo;
/** 错误信息抄送地址(多个邮件地址以";"分隔) */
private String errorCc;
/** 警告信息发送地址(多个邮件地址以";"分隔) */
private String warningTo;
/** 警告信息抄送地址(多个邮件地址以";"分隔) */
private String warningCc;
/** 通知信息发送地址(多个邮件地址以";"分隔) */
private String notifyTo;
/** 通知信息抄送地址(多个邮件地址以";"分隔) */
private String notifyCc;
/** 邮件主题 */
private String subject;
/** 邮件内容 */
private String content;
/** 邮件附件的文件名 */
private String[] attachFileNames;
public MailInfo(){
}
/**
* 获取邮件参数
*
* @return Properties props
* @throws GeneralSecurityException
*/
public Properties getProperties() throws GeneralSecurityException {
Properties props = new Properties();
props.setProperty("mail.transport.protocol", "smtp"); // 使用的协议(JavaMail规范要求)
props.setProperty("mail.smtp.port", getMailPort()); // SMTP 服务器 端口
props.setProperty("mail.smtp.host", getMailHost()); // 发件人的邮箱的 SMTP 服务器地址
props.setProperty("mail.smtp.auth", "true"); // 需要请求认证
// PS: 某些邮箱服务器要求 SMTP 连接需要使用 SSL 安全认证 (为了提高安全性, 邮箱支持SSL连接, 也可以自己开启),
// 如果无法连接邮件服务器, 仔细查看控制台打印的 log, 如果有有类似 “连接失败, 要求 SSL 安全连接” 等错误,
// 打开下面注释代码, 开启 SSL 安全连接。
// SMTP 服务器的端口 (非 SSL 连接的端口一般默认为 25, 可以不添加, 如果开启了 SSL 连接,
// 需要改为对应邮箱的 SMTP 服务器的端口, 具体可查看对应邮箱服务的帮助,
// QQ邮箱的SMTP(SLL)端口为465或587, 其他邮箱自行去查看)
// props.put("mail.smtp.port", getMailPort());
// props.put("mail.smtp.starttls.enable", "true");
// MailSSLSocketFactory sslSF = new MailSSLSocketFactory();
// sslSF.setTrustAllHosts(true);
// props.put("mail.smtp.ssl.enable", "true");
// props.put("mail.smtp.ssl.socketFactory", sslSF);
// props.put("mail.transport.protocol", "smtp");
return props;
}
get set 省略。。。
}
2.创建邮件发送类 MailSender.java 以及开启线程发送类 TheadMail.java
/**
* 邮件发送器
*
* @author eci
*
*/
public class MailSender {
/**
* 发送邮件
* 以文本格式和以html格式两种方式
* 这里选择以html格式
*/
public static void sendMail(MailInfo mailInfo, int mailType){
Runnable sendemail=new TheadEmail(mailInfo,mailType);
Thread thread=new Thread(sendemail);
thread.start();
}
/**
* 以文本格式发送邮件
*
* @param mailInfo 邮件信息
* @param mailType 邮件类型 1-error;2-warning;3-notify;
* @return
* @throws Exception
*/
public static boolean sendTextMail(MailInfo mailInfo, int mailType) throws Exception {
// 需要身份认证,创建一个密码验证器
MailAuthenticator authenticator = new MailAuthenticator(mailInfo.getUsername(), mailInfo.getPassword());
Properties prop = mailInfo.getProperties();
// 根据邮件会话属性和密码验证器构造一个发送邮件的session
Session sendMailSession = Session.getInstance(prop, authenticator);
sendMailSession.setDebug(true);
try {
// 根据session创建一个邮件消息
Message mailMessage = new MimeMessage(sendMailSession);
// 创建邮件发送者地址 例:发件人:华东信息 <[email protected]>
Address from = new InternetAddress(mailInfo.getUsername(), "华东信息", "UTF-8");
// 设置邮件消息的发送者
mailMessage.setFrom(from);
// 创建邮件的接收者地址 to:发送;cc:抄送
Address[][] maillToArr = getMailToAddress(mailInfo, mailType);
// 设置邮件消息的接收者,发送,抄送
if (maillToArr != null && maillToArr[0] != null && maillToArr[0].length > 0) {
mailMessage.setRecipients(Message.RecipientType.TO, maillToArr[0]);
}
if (maillToArr != null && maillToArr[1] != null && maillToArr[1].length > 0) {
mailMessage.setRecipients(Message.RecipientType.CC, maillToArr[1]);
}
// 设置邮件消息的主题
mailMessage.setSubject(mailInfo.getSubject());
// 设置邮件消息发送的时间
mailMessage.setSentDate(new Date());
// 设置邮件正文
mailMessage.setContent(mailInfo.getContent(), "text/html;charset=UTF-8");
// 发送邮件
Transport.send(mailMessage);
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
/**
* 以HTML格式发送邮件
*
* @param mailInfo 邮件信息
* @param mailType 邮件类型 1-error;2-warning;(默认)3-notify;
*/
public static boolean sendHtmlMail(MailInfo mailInfo, int mailType) throws Exception {
// 需要身份认证,创建一个密码验证器
MailAuthenticator authenticator = new MailAuthenticator(mailInfo.getUsername(), mailInfo.getPassword());
Properties prop = mailInfo.getProperties();
// 根据邮件会话属性和密码验证器构造一个发送邮件的session
Session sendMailSession = Session.getDefaultInstance(prop, authenticator);
sendMailSession.setDebug(true);
try {
// 根据session创建一个邮件消息
Message mailMessage = new MimeMessage(sendMailSession);
// 创建邮件发送者地址
Address from = new InternetAddress(mailInfo.getUsername(), "华东信息技术有限公司", "UTF-8");
// 设置邮件消息的发送者
mailMessage.setFrom(from);
// 创建邮件的接收者地址 to:发送;cc:抄送
Address[][] maillToArr = getMailToAddress(mailInfo, mailType);
// 设置邮件消息的接收者,发送,抄送
if (maillToArr != null && maillToArr[0] != null && maillToArr[0].length > 0) {
mailMessage.setRecipients(Message.RecipientType.TO, maillToArr[0]);
}
if (maillToArr != null && maillToArr[1] != null && maillToArr[1].length > 0) {
mailMessage.setRecipients(Message.RecipientType.CC, maillToArr[1]);
}
// 设置邮件消息的主题
mailMessage.setSubject(mailInfo.getSubject());
// 设置邮件消息发送的时间
mailMessage.setSentDate(Calendar.getInstance().getTime());
// MimeMultipart类是一个容器类,包含MimeBodyPart类型的对象
Multipart multiPart = new MimeMultipart();
// 创建一个包含HTML内容的MimeBodyPart
BodyPart bodyPart = new MimeBodyPart();
// 设置html邮件消息内容
bodyPart.setContent(mailInfo.getContent(), "text/html; charset=utf-8");
multiPart.addBodyPart(bodyPart);
//添加附件
if(mailInfo.getAttachFileNames().length != 0){
for(String attachFile : mailInfo.getAttachFileNames()){
bodyPart=new MimeBodyPart();
FileDataSource fds=new FileDataSource(attachFile); //得到数据源
bodyPart.setDataHandler(new DataHandler(fds)); //得到附件本身并放入BodyPart
bodyPart.setFileName(MimeUtility.encodeText(fds.getName())); //得到文件名并编码(防止中文文件名乱码)同样放入BodyPart
multiPart.addBodyPart(bodyPart);
}
}
// 设置邮件消息的主要内容
mailMessage.setContent(multiPart);
// 发送邮件
Transport.send(mailMessage);
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
/**
* 创建发送邮件列表地址对象
*
* @param mailInfo 邮件信息
* @param mailType 邮件类型 1-error;2-warning;(默认)3-notify;
* @return Address[0]:发送地址数组;Address[1]:抄送地址数组
* @throws UnsupportedEncodingException
*/
private static Address[][] getMailToAddress(MailInfo mailInfo, int mailType) throws Exception {
Address[] toAdds = null;
Address[] ccAdds = null;
//收件人不为空
if(!"".equals(mailInfo.getNotifyTo()) && mailInfo.getNotifyTo() != null){
String[] toMails = mailInfo.getNotifyTo().split(";");
toAdds = new InternetAddress[toMails.length];
for (int index = 0; index < toMails.length; index++) {
toAdds[index] = new InternetAddress(toMails[index]);
}
}
//抄送人不为空
if(!"".equals(mailInfo.getNotifyCc()) && mailInfo.getNotifyCc() != null){
String[] ccMails = mailInfo.getNotifyCc().split(";");
ccAdds = new InternetAddress[ccMails.length];
for (int index = 0; index < ccMails.length; index++) {
ccAdds[index] = new InternetAddress(ccMails[index]);
}
}
Address[][] result = { toAdds, ccAdds };
return result;
}
}
//后台发送邮件
class TheadEmail implements Runnable{
private MailInfo mailInfo;
private int mailType;
TheadEmail(MailInfo mailInfo,int mailType){
this.mailInfo = mailInfo;
this.mailType = mailType;
}
@Override
public void run() {
try {
MailSender.sendHtmlMail(mailInfo,mailType);
} catch (Exception e) {
System.out.println("邮件发送失败");
e.printStackTrace();
}
}
}
3.创建邮箱登录验证类MailAuthenticator.java
/**
* 身份验证器
* @author eci
*
*/
public class MailAuthenticator extends Authenticator{
/** 用户账号 */
private String userName = null;
/** 用户口令 */
private String password = null;
/**
* @param userName
* @param password
*/
public MailAuthenticator(String userName, String password) {
this.userName = userName;
this.password = password;
}
/**
* 身份验证
* @return
*/
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, password);
}
}
4.测试类
public class SendMailProvider {
private static AbstractMap<String, Properties> map = new HashMap<String, Properties>();
public static void main(String[] args) throws Exception {
MailInfo mailInfo = getMailInfo();
// mailSender.sendTextMail(mailInfo, 3);
MailSender.sendMail(mailInfo, 3);
}
/**
* 构建MailInfo对象
* @return
* @throws Exception
*/
public static MailInfo getMailInfo() throws Exception {
Properties props = LoadProperties("app.properties");
String host = props.getProperty("mail.smtp.host"); // SMTP 服务器地址
String port = props.getProperty("mail.smtp.port"); // 端口
String userName = props.getProperty("mail.user"); //账号
String password = props.getProperty("mail.password");//登录密码
MailInfo info = new MailInfo();
info.setMailHost(host);
info.setUsername(userName);
info.setPassword(password);
info.setMailPort(port);
//文件接收人
info.setNotifyTo("[email protected]");
//文件抄收人
info.setNotifyCc("[email protected]");
info.setSubject("今天要加班");
info.setContent("由于工作需要,今天各部门加班到10点,大家务必遵守、、、");
// info.setAttachFileNames(new String[]{"E:\\sendMail.jpg","E:\\公司班车路线2016年6月调整版.xls"});//添加附件
info.setAttachFileNames(new String[]{});//添加附件
return info;
}
public static Properties LoadProperties(String propertiesFileName) throws Exception {
if (!map.containsKey(propertiesFileName)) {
InputStream inputStream = new FileInputStream("D:\\TFS项目\\公司JAVA开发框架\\源代码\\后台\\WebEntry\\WebContent\\WEB-INF\\classes\\"+propertiesFileName);
Properties props = new Properties();
props.load(inputStream);
map.put(propertiesFileName, props);
inputStream.close();
}
return map.get(propertiesFileName);
}
}