利用JavaMail发送邮件

来源:互联网 发布:怎么下载python安装包 编辑:程序博客网 时间:2024/05/22 15:55

       这次项目里有流程审批操作,涉及到的工作流里流程控制都是自己写的,其中发送通知有站内信、短信和邮件,发送邮件我选择了JavaMail,比较通用。引入一个核心jar即可(mail.jar),java代码如下:

import java.util.Properties;import java.util.regex.Matcher;import java.util.regex.Pattern;import javax.mail.Session;import javax.mail.Transport;import javax.mail.internet.InternetAddress;import javax.mail.internet.MimeMessage;import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;public class MailSend {public static String host;//smtp服务器public static String user;//用户名,即发送邮件的邮箱public static String password;//密码public static String fromMailAddress;//发送人地址public static String from;//发送人要显示的名称protected Log logger = LogFactory.getLog(getClass());@SuppressWarnings("static-access")public MailSend(String host,String user,String password,String fromMailAddress,String from){this.host=host;this.user=user;this.password=password;this.fromMailAddress =fromMailAddress;this.from=from;}public void send(String[] toMailAddress, String subject,String content) {Properties props = new Properties();props.put("mail.smtp.host", host);// 指定SMTP服务器props.put("mail.smtp.auth", "true");// 指定是否需要SMTP验证try {Session mailSession = Session.getInstance(props);mailSession.setDebug(false);// 是否在控制台显示debug信息MimeMessage message = new MimeMessage(mailSession);String nick=javax.mail.internet.MimeUtility.encodeText (from, "utf-8", null);message.setFrom(new InternetAddress(nick+" <"+fromMailAddress+">"));InternetAddress[] sendTo = new InternetAddress[toMailAddress.length];for (int i = 0; i < toMailAddress.length; i++) {sendTo[i] = new InternetAddress(toMailAddress[i]);}message.setRecipients(javax.mail.internet.MimeMessage.RecipientType.BCC, sendTo);message.setSubject(subject, "utf-8");// 邮件主题message.setContent(content, "text/html;charset=utf-8");message.saveChanges();Transport transport = mailSession.getTransport("smtp");transport.connect(host,user,password);transport.sendMessage(message, message.getAllRecipients());transport.close();} catch (Exception e) {logger.info("send mail error:   "+e.toString());e.printStackTrace();}}public static boolean  isNameAdressFormat(String email){           boolean isExist = false;           Pattern p = Pattern.compile("(\\w[-._\\w]*\\w@\\w[-._\\w]*\\w\\.\\w{2,3})");           Matcher m = p.matcher(email);           boolean b = m.matches();           if(b) {                isExist=true;            } else {                System.out.println(email +" error email is :无效邮件地址----------");            }           return isExist;        }  public static void main(String[] args) {String rec[] =new String[2];rec[0]=("123456789@qq.com");rec[1]=("123456789@163.com");MailSend ms=new MailSend("smtp.163.com","123456","abc123","123456789@163.com","hehe");ms.send(rec,"aaaaaaa","ddddddd");}



0 0
原创粉丝点击