java发邮件工具类

最近为了给程序加个监控,想到了先用个异常发送邮件来提醒。就写了个发邮件得工具类。

用在linux上得话注意下jar的版本。我用的是:

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

工具类代码如下:

package com.mg.util;

import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Properties;
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.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

public class EmailUtils {
private static MimeMessage mimeMsg;  //发送短信类
private static Session session; //邮件会话
private static Properties props;  //系统配置
private static final String from = "xxxx@163.com";//发件人
private static final String nick = "xxx公司";//发件人昵称
private static final String username = "xxxx@163.com";//账号
private static final String password = "your password"; //密码 
private static final String smtp = "smtp.163.com";  
private static Multipart mp;   //短信属性类

private final static Logger LOG = Logger.getLogger(EmailUtils.class);
static {
if(null == props) {
props = System.getProperties();
}
props.put("mail.smtp.host", smtp);
// props.put("mail.transport.protocol", "smtp");
try {
LOG.info("获取会话对象--->");
session = Session.getDefaultInstance(props, null);
LOG.info("创建MIME邮件对象--->");
mimeMsg = new MimeMessage(session);  
mp = new MimeMultipart(); 
} catch(Exception e) {
LOG.info("获取邮件对象失败:"+e.getMessage());
}
}
/**
* 群发邮件
* @param toList 收件邮箱集合
* @param copytoList 抄送邮箱集合
* @param theme 主题
* @param content 发送内容
* @return
*/
public static boolean sendEmail(List<String> toList,List<String> copytoList,String theme,String content) {
String to = getMailList(toList);
String copyto = getMailList(copytoList);
return sendEmail(to,copyto,theme,content);
}
/**
* 发送邮件给一个人,抄送给一个人
* @param to 收件邮箱
* @param copyto 抄送邮箱
* @param theme 主题
* @param content 发送内容
* @return
*/
public static boolean sendEmail(String to,String copyto,String theme,String content) {
//验证
checkAuth(true);
if(!setEmailTheme(theme)) {//主题
return false;
}
if(!setFrom(from)) {//发件人
return false;
}
if(!setTo(to)) {//收件人
return false;
}
if(!setEmailContent(content)) {//邮件正文
return false;
}
if(!setCopyTo(copyto)) {//抄送人
return false;
}
return sendOut();
}
private static boolean sendOut() {
try {
mimeMsg.setContent(mp);
mimeMsg.saveChanges();
LOG.info("邮件发送中...");
Transport transport = session.getTransport("smtp");  
transport.connect((String) props.get("mail.smtp.host"), username, password);  
transport.sendMessage(mimeMsg, mimeMsg.getAllRecipients());
LOG.info("邮件发送成功...");
transport.close(); 
return true;
} catch (MessagingException e) {
LOG.info("邮件发送失败:"+e.getMessage());
}  
return false;
}
/**
* 把邮箱集合转成String类型
* @param emailList
* @return
*/
private static String getMailList(List<String> emailList) {
StringBuffer mails = new StringBuffer("");
if(null == emailList) {
return "";
} else {
for(String email : emailList) {
mails.append(email).append(",");
}
}
if(mails.length() > 0) {
mails.setLength(mails.length() - 1);
}
return mails.toString();
}
/**
* 定义抄送人
* @param copyTo
* @return
*/
private static boolean setCopyTo(String copyTo) {
LOG.info("定义抄送人:"+copyTo);
try {
mimeMsg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(copyTo));
return true;
} catch (MessagingException e) {
LOG.info("定义抄送人失败:"+e.getMessage());
return false;

}
/**
* 定义邮件内容
* @param content
* @return
*/
private static boolean setEmailContent(String content) {
LOG.info("定义邮件内容:"+content);
BodyPart bp = new MimeBodyPart();  
try {
bp.setContent("" + content, "text/html;charset=GBK");
mp.addBodyPart(bp);  
return true;
} catch (MessagingException e) {
LOG.info("定义邮件内容失败:"+e.getMessage());
return false;
}  
}
/**
* 定义收件人
* @param to
* @return
*/
private static boolean setTo(String to) {
LOG.info("定义收件人:"+to);
if(StringUtils.isBlank(to)) {
LOG.info("定义收件人失败:收件人为空...");
return false;
}
try {
mimeMsg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
return true;
} catch (Exception e) {
LOG.info("定义收件人失败:"+e.getMessage());
return false;
}
}
/**
* 定义发件人
* @param from
* @return
*/
private static boolean setFrom(String from) {
LOG.info("定义发件人:"+from);
if(StringUtils.isBlank(from)) {
LOG.info("定义发件人昵称失败:发件人为空");
return false;
}
String nickName = "";
try {
nickName = MimeUtility.encodeText(nick);
} catch (UnsupportedEncodingException e) {
LOG.info("定义发件昵称失败:"+e.getMessage());
}
try {
mimeMsg.setFrom(new InternetAddress(from,nickName));
return true;
} catch (MessagingException e) {
LOG.info("定义发件人失败:"+e.getMessage());
return false;
} catch (UnsupportedEncodingException e) {
LOG.info("定义发件人昵称失败:"+e.getMessage());
return false;
}
}
/**
* 定义邮件主题
* @param theme
* @return
*/
private static boolean setEmailTheme(String theme) {
LOG.info("定义邮件主题:"+theme);
try {
mimeMsg.setSubject(theme);
return true;
} catch (MessagingException e) {
LOG.info("定义邮件主题失败:"+e.getMessage());
return false;
}
}
/**
* 定义SMTP是否需要验证
* @param need 是否需要验证
*/
private static void checkAuth(boolean need) {
LOG.info("设置smtp身份认证:mail.smtp.auth = " + need);  
if (props == null)  
   props = System.getProperties();

if (need) {  
   props.put("mail.smtp.auth", "true");  
} else {  
   props.put("mail.smtp.auth", "false");  
}  
}
}

以上直接调用静态的方法即可:

public static void main(String[] args) {
List<String> to = new ArrayList<String>();//也可以读取配置文件来获取
to.add("xxx@163.com");
to.add("yyy@163.com");
List<String> copyto = new ArrayList<String>();
copyto.add("xxxxxxxx@qq.com");
copyto.add("xxxxxx@qq.com");
String subject = "测试用";// 邮件标题  
String content = "测试  测试,come in !";// 邮件内容

sendEmail(to,copyto,subject,content);//批量发送
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值