java mail发送邮件
最近做测试的时候,需要发送邮件,但是实际的邮件收件人,必须是测试或开发,不想每次都改收件人。
所以自己重新写了个发送邮件程序:
1.收件人默认配置开发或者测试;
2.调用的实时发送邮件接口,会实时发送,提高测试效率;
3.收件人,抄送人,密送人会在邮件标题里面列出来,方便测试检查。
后期增加附件的发送。
认证类
package com.info.util; import javax.mail.Authenticator; import javax.mail.PasswordAuthentication; /** * 邮件 * 自定义认证器 * @author menghu * */ public class MyAuthenticator extends Authenticator { String userName = null; String password = null; public MyAuthenticator() { } public MyAuthenticator(String username, String password) { this.userName = username; this.password = password; } protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(userName, password); } }
自定义邮件对象
package com.info.util; /** * * 邮件 * 发送邮件工具类 * */ import java.util.Properties; public class MailSenderInfo { // 发送邮件的服务器的IP和端口 private String mailServerHost; private String mailServerPort; // 邮件发送者的地址 private String fromAddress; // 邮件接收者的地址 private String toAddress; // 邮件抄送者的地址 private String ccAddress; // 邮件密送者的地址 private String bccAddress; // 登陆邮件发送服务器的用户名和密码 private String userName; private String password; // 是否需要身份验证 private boolean validate = false; // 邮件主题 private String subject; // 邮件的文本内容 private String content; // 邮件附件的文件名 private String[] attachFileNames; /** * 获得邮件会话属性 */ public Properties getProperties() { Properties p = new Properties(); p.put("mail.smtp.host", this.mailServerHost); //p.put("mail.smtp.port", this.mailServerPort); p.put("mail.smtp.auth", validate ? "true" : "false"); return p; } public String getMailServerHost() { return mailServerHost; } public void setMailServerHost(String mailServerHost) { this.mailServerHost = mailServerHost; } public String getMailServerPort() { return mailServerPort; } public void setMailServerPort(String mailServerPort) { this.mailServerPort = mailServerPort; } public boolean isValidate() { return validate; } public void setValidate(boolean validate) { this.validate = validate; } public String[] getAttachFileNames() { return attachFileNames; } public void setAttachFileNames(String[] fileNames) { this.attachFileNames = fileNames; } public String getFromAddress() { return fromAddress; } public void setFromAddress(String fromAddress) { this.fromAddress = fromAddress; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getToAddress() { return toAddress; } public void setToAddress(String toAddress) { this.toAddress = toAddress; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getSubject() { return subject; } public void setSubject(String subject) { this.subject = subject; } public String getContent() { return content; } public void setContent(String textContent) { this.content = textContent; } public String getCcAddress() { return ccAddress; } public void setCcAddress(String ccAddress) { this.ccAddress = ccAddress; } public String getBccAddress() { return bccAddress; } public void setBccAddress(String bccAddress) { this.bccAddress = bccAddress; } }
发送邮件类
package com.info.util; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Properties; import javax.mail.Address; 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.MimeMultipart; /** * 邮件 简单邮件(不带附件的邮件)发送器 * * @author menghu * */ public class SimpleMailSender { /** * 以文本格式发送邮件 * * @param mailInfo * 待发送的邮件的信息 */ @SuppressWarnings({ "rawtypes", "unchecked" }) public boolean sendTextMail(MailSenderInfo mailInfo) { // 判断是否需要身份认证 MyAuthenticator authenticator = null; Properties pro = mailInfo.getProperties(); if (mailInfo.isValidate()) { // 如果需要身份认证,则创建一个密码验证器 authenticator = new MyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword()); } // 根据邮件会话属性和密码验证器构造一个发送邮件的session Session sendMailSession = Session.getDefaultInstance(pro, authenticator); try { // 根据session创建一个邮件消息 Message mailMessage = new MimeMessage(sendMailSession); // 创建邮件发送者地址 Address from = new InternetAddress(mailInfo.getFromAddress()); // 设置邮件消息的发送者 mailMessage.setFrom(from); // 创建邮件的接收者地址,并设置到邮件消息中 List toList = string2List(mailInfo.getToAddress()); InternetAddress[] tos = (InternetAddress[]) toList.toArray(new InternetAddress[toList.size()]); mailMessage.setRecipients(Message.RecipientType.TO, tos); List ccList = string2List(mailInfo.getCcAddress()); InternetAddress[] ccs = (InternetAddress[]) ccList.toArray(new InternetAddress[ccList.size()]); mailMessage.setRecipients(Message.RecipientType.CC, ccs); List bccList = string2List(mailInfo.getBccAddress()); InternetAddress[] bccs = (InternetAddress[]) bccList.toArray(new InternetAddress[bccList.size()]); mailMessage.setRecipients(Message.RecipientType.CC, bccs); // 设置邮件消息的主题 mailMessage.setSubject(mailInfo.getSubject()); // 设置邮件消息发送的时间 mailMessage.setSentDate(new Date()); // 设置邮件消息的主要内容 String mailContent = mailInfo.getContent(); mailMessage.setText(mailContent); // 发送邮件 Transport.send(mailMessage); return true; } catch (MessagingException ex) { ex.printStackTrace(); } return false; } /** * 以HTML格式发送邮件 * * @param mailInfo * 待发送的邮件信息 */ @SuppressWarnings({ "rawtypes", "unchecked" }) public static boolean sendHtmlMail(MailSenderInfo mailInfo) { // 判断是否需要身份认证 MyAuthenticator authenticator = null; Properties pro = mailInfo.getProperties(); // 如果需要身份认证,则创建一个密码验证器 if (mailInfo.isValidate()) { authenticator = new MyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword()); } // 根据邮件会话属性和密码验证器构造一个发送邮件的session Session sendMailSession = Session.getDefaultInstance(pro, authenticator); try { // 根据session创建一个邮件消息 Message mailMessage = new MimeMessage(sendMailSession); // 创建邮件发送者地址 Address from = new InternetAddress(mailInfo.getFromAddress()); // 设置邮件消息的发送者 mailMessage.setFrom(from); // 创建邮件的接收者地址,并设置到邮件消息中 List toList = string2List(mailInfo.getToAddress()); InternetAddress[] tos = (InternetAddress[]) toList.toArray(new InternetAddress[toList.size()]); mailMessage.setRecipients(Message.RecipientType.TO, tos); List ccList = string2List(mailInfo.getCcAddress()); InternetAddress[] ccs = (InternetAddress[]) ccList.toArray(new InternetAddress[ccList.size()]); mailMessage.setRecipients(Message.RecipientType.CC, ccs); List bccList = string2List(mailInfo.getBccAddress()); InternetAddress[] bccs = (InternetAddress[]) bccList.toArray(new InternetAddress[bccList.size()]); mailMessage.setRecipients(Message.RecipientType.CC, bccs); // 设置邮件消息的主题 mailMessage.setSubject(mailInfo.getSubject()); // 设置邮件消息发送的时间 mailMessage.setSentDate(new Date()); // MiniMultipart类是一个容器类,包含MimeBodyPart类型的对象 Multipart mainPart = new MimeMultipart(); // 创建一个包含HTML内容的MimeBodyPart BodyPart html = new MimeBodyPart(); // 设置HTML内容 html.setContent(mailInfo.getContent(), "text/html; charset=utf-8"); mainPart.addBodyPart(html); // 将MiniMultipart对象设置为邮件内容 mailMessage.setContent(mainPart); // 发送邮件 Transport.send(mailMessage); return true; } catch (MessagingException ex) { ex.printStackTrace(); } return false; } @SuppressWarnings({ "rawtypes", "unchecked" }) private static List string2List(String strs) throws AddressException { List list = new ArrayList();// 不能使用string类型的类型,这样只能发送一个收件人 String[] tosStr = strs.split(";");// 对输入的多个邮件进行逗号分割 for (String str : tosStr) { if (CheckUtils.checkStringNotNull(str)) { list.add(new InternetAddress(str)); } } return list; } }
发送测试类
package com.info.util.test; import java.math.BigDecimal; import java.sql.SQLException; import java.util.List; import java.util.Map; import junit.framework.TestCase; import org.apache.log4j.PropertyConfigurator; import org.hibernate.HibernateException; import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer; import org.springframework.beans.factory.xml.XmlBeanFactory; import org.springframework.core.io.FileSystemResource; import org.springframework.core.io.Resource; import org.springframework.jdbc.core.simple.SimpleJdbcTemplate; import com.info.util.ADUtils; import com.info.util.CheckUtils; import com.info.util.MailSenderInfo; import com.info.util.SimpleMailSender; import com.mchange.v2.c3p0.ComboPooledDataSource; public class TestMail extends TestCase { private XmlBeanFactory parent = null; private XmlBeanFactory factory = null; @Override protected void setUp() throws Exception { String filePath = TestMail.class.getResource("/").getPath(); System.out.println(filePath); PropertyConfigurator.configure("WebRoot/WEB-INF/log4j.properties"); PropertyPlaceholderConfigurer cfg = new PropertyPlaceholderConfigurer(); // cfg.setLocation(new ClassPathResource("jdbc.properties")); Resource jdbcResource = new FileSystemResource("WebRoot/WEB-INF/jdbc.properties"); cfg.setLocation(jdbcResource); Resource resource = new FileSystemResource("WebRoot/WEB-INF/applicationContext.xml"); parent = new XmlBeanFactory(resource); cfg.postProcessBeanFactory(parent);// 必须采用延后加载 } @Override protected void tearDown() throws Exception { // TODO Auto-generated method stub super.tearDown(); } public void testSendMail() throws HibernateException, SQLException { ComboPooledDataSource comboPooledDataSource = (ComboPooledDataSource) parent.getBean("dataSource"); SimpleJdbcTemplate jdbcTemplate = (SimpleJdbcTemplate) parent.getBean("jdbcTemplate"); System.out.println(comboPooledDataSource.getJdbcUrl()); String queryStr = "SELECT * from SYS_EMAIL_SEND t WHERE t.TIMESTAMP IS NULL"; String updateStr = "UPDATE SYS_EMAIL_SEND t SET t.TIMESTAMP = ‘-99‘ WHERE t.EMAIL_ID = ?"; //判断数据库配置信息,只针对待发送邮件的数据库 if ("xxx".equals(comboPooledDataSource.getJdbcUrl())) { List<Map<String, Object>> emailList = jdbcTemplate.queryForList(queryStr); for (Map<String, Object> email : emailList) { MailSenderInfo mailInfo = new MailSenderInfo(); Long email_id = ((BigDecimal) email.get("email_id")).longValue(); String recipients = (String) email.get("recipients"); String carbon_copys = (String) email.get("carbon_copys"); String blind_carbon_copys = (String) email.get("blind_carbon_copys"); String title = "[测试邮件]" + (String) email.get("title"); if (CheckUtils.checkStringNotNull(recipients)) { title = title + " to:" + emails2ADNames(recipients); } if (CheckUtils.checkStringNotNull(carbon_copys)) { title = title + " cc:" + emails2ADNames(carbon_copys); } if (CheckUtils.checkStringNotNull(blind_carbon_copys)) { title = title + " bcc:" + emails2ADNames(blind_carbon_copys); } String content = (String) email.get("content"); StringBuilder toAddress = new StringBuilder(); toAddress.append("xxx"); mailInfo.setToAddress(toAddress.toString()); mailInfo.setCcAddress(""); mailInfo.setBccAddress(""); mailInfo.setSubject(title); mailInfo.setContent(content); this.sendMail(mailInfo); jdbcTemplate.update(updateStr, email_id); } } } @SuppressWarnings("static-access") private void sendMail(MailSenderInfo mailInfo) { mailInfo.setMailServerHost("xxx"); // mailInfo.setMailServerPort("25"); mailInfo.setValidate(true); mailInfo.setUserName("xxxx"); mailInfo.setPassword("xxx"); mailInfo.setFromAddress("xxx"); // 这个类主要来发送邮件 SimpleMailSender sms = new SimpleMailSender(); // sms.sendTextMail(mailInfo);// 发送文体格式 sms.sendHtmlMail(mailInfo);// 发送html格式 } private String emails2ADNames(String emailStr) { String[] strArr = emailStr.split(";"); String adString = ""; for (String str : strArr) { adString += ADUtils.queryDispalyNameByEmail(str); } return adString; } }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。