可能最近写博客时间不会很多,最近又在搞一个项目了。
发送邮件的类,我以前写过,不过写的不是接口封装的,现在自己项目用到了,就重新写了一下,现在把它分享出来给大家。
用得到的就可以拿过去,基本上不需要改什么就可以用的。
在这里我用到了3个类加一个接口。
其中一个类是实现发送邮件的。
另外一个类是发邮件方的配置类。
还有一个类是用来加密的。
接口的话,你只需要写一个实现类实现就可以了。
#MyEmail
package com.uifuture.utils.email; /** * Created with IntelliJ IDEA. * User: 陈浩翔. * Date: 2017/3/15. * Time: 下午 12:33. * Explain:我们的发件邮箱类 */ public class MyEmail { private String mainAdd;//发件邮箱地址 private String mainName;//发件人的名称 private String password;//发件邮箱密码-也叫授权码 private String port;//发件邮箱端口 private String mailHost;//设置邮件服务器主机名 private String mailProtocol;// 发送邮件协议名称 private String subject;//邮件内容:主题 private String activeMailAdd;//邮件激活地址,未带状态以及用户id private String serviceMail;//客服邮箱 private String helpCenterUrl;//网站帮助中心地址 private String content;//邮件的正文内容 public MyEmail() { } public MyEmail(String mainAdd, String mainName, String password, String port, String mailHost, String mailProtocol, String subject, String activeMailAdd, String serviceMail, String helpCenterUrl, String content) { this.mainAdd = mainAdd; this.mainName = mainName; this.password = password; this.port = port; this.mailHost = mailHost; this.mailProtocol = mailProtocol; this.subject = subject; this.activeMailAdd = activeMailAdd; this.serviceMail = serviceMail; this.helpCenterUrl = helpCenterUrl; this.content = content; } public String getMainAdd() { return mainAdd; } public void setMainAdd(String mainAdd) { this.mainAdd = mainAdd; } public String getMainName() { return mainName; } public void setMainName(String mainName) { this.mainName = mainName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getPort() { return port; } public void setPort(String port) { this.port = port; } public String getMailHost() { return mailHost; } public void setMailHost(String mailHost) { this.mailHost = mailHost; } public String getMailProtocol() { return mailProtocol; } public void setMailProtocol(String mailProtocol) { this.mailProtocol = mailProtocol; } public String getSubject() { return subject; } public void setSubject(String subject) { this.subject = subject; } public String getActiveMailAdd() { return activeMailAdd; } public void setActiveMailAdd(String activeMailAdd) { this.activeMailAdd = activeMailAdd; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getServiceMail() { return serviceMail; } public void setServiceMail(String serviceMail) { this.serviceMail = serviceMail; } public String getHelpCenterUrl() { return helpCenterUrl; } public void setHelpCenterUrl(String helpCenterUrl) { this.helpCenterUrl = helpCenterUrl; } }
#SendEmail
package com.uifuture.utils.email; /** * Created with IntelliJ IDEA. * User: 陈浩翔. * Date: 2017/3/15. * Time: 下午 12:20. * Explain:用户发送邮件必须实现的接口 */ public interface SendEmail { public String getId(); public String getToken(); public String getName(); public String getEmail(); }
#PasswordUtil
package com.uifuture.utils.pass; /** * 密码加密工具 */ public class PasswordUtil { /** * 用户登录等密码的加密方法 * @param password * @param salt * @return */ public static String getPassword(String password, String salt) { return MD5Util.md5Encode(MD5Util.md5Encode(password) + salt); } /** * 生成 token 的方式-验证的令牌 * 在用户点击验证邮箱地址时使用,密码使用的是加密后的密码! * @param loginName * @param password * @return */ public static String getToken(String loginName, String password){ return getPassword(MD5Util.md5Encode(loginName+password), MD5Util.md5Encode(password)); } }
#SendEmailCallable
package com.uifuture.utils.email; import com.sun.mail.util.MailSSLSocketFactory; import org.apache.log4j.Logger; import javax.mail.*; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import java.io.UnsupportedEncodingException; import java.security.GeneralSecurityException; import java.util.Properties; import java.util.concurrent.Callable; /** * Created with IntelliJ IDEA. * User: 陈浩翔. * Date: 2017/3/15. * Time: 下午 1:07. * Explain:发送邮件的实现类,此类继承了Thread,实现多线程发送邮件,调用start方法运行run函数 */ public class SendEmailCallable implements Callable { private static Logger logger = Logger.getLogger(SendEmailCallable.class); private MyEmail myEmail; private SendEmail sendEmail; public SendEmailCallable() { } public SendEmailCallable(MyEmail myEmail, SendEmail sendEmail) { this.myEmail = myEmail; this.sendEmail = sendEmail; } public Object call() throws Exception { // 跟smtp服务器建立一个连接 Properties p = new Properties(); // 设置邮件服务器主机名 p.setProperty("mail.host", myEmail.getMailHost());// 指定邮件服务器,默认端口 25 // 发送服务器需要身份验证 p.setProperty("mail.smtp.auth", "true");// 要采用指定用户名密码的方式去认证 // 发送邮件协议名称 p.setProperty("mail.transport.protocol", myEmail.getMailProtocol()); p.setProperty("mail.smtp.port", "465"); // 开启SSL加密,否则会失败 MailSSLSocketFactory sf = null; try { sf = new MailSSLSocketFactory(); } catch (GeneralSecurityException e1) { logger.error("开启SSL加密失败,出现GeneralSecurityException异常!用户ID为:"+sendEmail.getId()+",给" + sendEmail.getToken() + "发送邮件失败!"); e1.printStackTrace(); } // 开启debug调试,以便在控制台查看 //p.setProperty("mail.debug", "true"); sf.setTrustAllHosts(true); p.put("mail.smtp.ssl.enable", "true"); p.put("mail.smtp.ssl.socketFactory", sf); Session session = Session.getDefaultInstance(p, new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { // 用户名可以用邮箱的别名 PasswordAuthentication pa = new PasswordAuthentication( myEmail.getMainAdd(), myEmail.getPassword()); // 后面的字符是授权码! return pa; } }); //session.setDebug(true);// 设置打开调试状态 try { // 声明一个Message对象(代表一封邮件),从session中创建 MimeMessage msg = new MimeMessage(session); // 邮件信息封装 // 1发件人 msg.setFrom(new InternetAddress(myEmail.getMainAdd(), myEmail.getMainName(), "UTF-8")); // 2收件人 msg.setRecipient(Message.RecipientType.TO, new InternetAddress(sendEmail.getEmail())); // 3邮件内容:主题、内容 msg.setSubject(sendEmail.getName() + "," + myEmail.getSubject()); // StringBuilder是线程不安全的,但是速度快,这里因为只会有这个线程来访问,所以可以用这个 StringBuilder sbd = new StringBuilder(); sbd.append("<!DOCTYPE html><html><head><meta charset='UTF-8'>" + "<title>UIF邮箱激活</title>" + "</head><body>" + "<table style='background: #fff; border-collapse: collapse; border-spacing: 0; color: #222; font-size: 16px; height: 100%; margin: 0; padding: 0; width: 100%'bgcolor='#fff'>" + "<tbody><tr><td style='-moz-hyphens: auto; -webkit-hyphens: auto; border-collapse: collapse !important; color: #222; font-size: 16px; hyphens: auto; margin: 0; padding: 0; text-align: center; word-break: break-word'valign='top'align='center'>" + "<center><table style='border-collapse: collapse; border-spacing: 0; font-size: 16px; line-height: 1.5; margin: 0 auto; max-width: 680px; min-width: 300px; width: 95%'>" + "<tbody><tr><td style='-moz-hyphens: auto; -webkit-hyphens: auto; border-collapse: collapse !important; color: #222; font-family: font-size: 16px; hyphens: auto; margin: 0; padding: 0; word-break: break-word'>" + "<hr style='background: #ddd; border: none; color: #ddd; height: 1px; margin: 20px 0 30px'>" + "<table style='border-collapse: collapse; border-spacing: 0'width='100%'>" + "<tbody><tr><td style='-moz-hyphens: auto; -webkit-hyphens: auto; border-collapse: collapse !important; color: #222; font-size: 16px; hyphens: auto; margin: 0; padding: 0; word-break: break-word'>" + "<div><p style='color: #222; font-size: 16px; margin: 0 0 10px; padding: 0'>" + sendEmail.getName() + ",你好!" + "</p><p style='color: #222; font-size: 16px; margin: 0 0 10px; padding: 0'>" + myEmail.getContent() + "</p><p style='color: #222; font-size: 16px; margin: 24px 0; padding: 0'>" + "<a href='" + myEmail.getActiveMailAdd() + "/" + sendEmail.getToken() + "'target='_blank'style='background: #83a198; border-radius: 4px; color: #fff; padding: 8px 16px; text-decoration: none; word-break: break-all'>" + myEmail.getActiveMailAdd() + "/" + sendEmail.getToken() + "</a></p><p style='color: #999999; font-size: 12px; margin: 0 0 10px; padding: 0'>" + "如果你没有使用过UIFuture,请忽略此邮件。" + "</p></div></td></tr></tbody></table>" + "<hr style='background: #ddd; border: none; color: #ddd; height: 1px; margin: 20px 0'>" + "<table style='border-collapse: collapse; border-spacing: 0'width='100%'>" + "<tbody><tr><td colspan='2'style='-moz-hyphens: auto; -webkit-hyphens: auto; border-collapse: collapse !important; color: #222;font-size: 16px; hyphens: auto; margin: 0; padding: 0; word-break: break-word'align='center'>" + "<p style='color: #999999; font-size: 12px; margin: 0 0 10px; padding: 0'>" + "如有疑问请联系我们:" + "<a href='mailto:" + myEmail.getServiceMail() + "'style='color: #999999; text-decoration: underline'target='_blank'>" + myEmail.getServiceMail() + "</a>" + "或进入" + "<a href='" + myEmail.getHelpCenterUrl() + "'target='_blank'style='color: #999999; text-decoration: underline'>帮助中心" + "</a></p></td></tr></tbody></table></td></tr></tbody></table></center></td></tr></tbody></table></body></html>"); msg.setContent(sbd.toString(), "text/html;charset=utf-8");// 发html格式的文本 // 发送动作 Transport.send(msg); logger.info("用户ID为:"+sendEmail.getId()+",给" + sendEmail.getEmail() + "发送邮件成功..."); return 1; } catch (AddressException e) { logger.error("用户ID为:"+sendEmail.getId()+",给" + sendEmail.getEmail() + "发送邮件失败,异常信息:" + e.getMessage()); return "用户ID为:"+sendEmail.getId()+",给" + sendEmail.getEmail() + "发送邮件失败,异常信息:" + e.getMessage(); } catch (MessagingException e) { logger.error("用户ID为:"+sendEmail.getId()+",给" + sendEmail.getEmail() + "发送邮件失败,异常信息:" + e.getMessage()); return "用户ID为:"+sendEmail.getId()+",给" + sendEmail.getEmail() + "发送邮件失败,异常信息:" + e.getMessage(); } catch (UnsupportedEncodingException e) { logger.error("用户ID为:"+sendEmail.getId()+",给" + sendEmail.getEmail() + "发送邮件失败,异常信息:" + e.getMessage()); return "用户ID为:"+sendEmail.getId()+",给" + sendEmail.getEmail() + "发送邮件失败,异常信息:" + e.getMessage(); } } }
#TestMail测试类
package com.uifuture.utilsTest; import com.uifuture.utils.UUID; import com.uifuture.utils.email.MyEmail; import com.uifuture.utils.email.SendEmail; import com.uifuture.utils.email.SendEmailCallable; import com.uifuture.utils.pass.PasswordUtil; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; /** * Created with IntelliJ IDEA. * User: 陈浩翔. * Date: 2017/3/15. * Time: 下午 12:28. * Explain:测试邮件发送类 */ public class TestMail{ static String mail = "**@qq.com"; //通过 //"**@outlook.com"; //通过 //"**@sina.com";//通过 //"**@163.com"; //163 public static void main(String[] args) throws ExecutionException, InterruptedException { MyEmail myEmail = new MyEmail(); myEmail.setMainAdd("**@uifuture.com"); myEmail.setMainName("UIFuture"); myEmail.setPassword("******");//密码 myEmail.setPort("465"); myEmail.setActiveMailAdd("http://uifuture.com/active/email"); myEmail.setContent("感谢选择UIFuture,祝您使用愉快,点击下面链接验证邮箱(邮箱验证30分钟后过期):"); myEmail.setHelpCenterUrl("http://uifuture.com/helpCenterUrl"); myEmail.setMailHost("smtp.uifuture.com"); myEmail.setServiceMail("**@uifuture.com");//客服邮箱 myEmail.setMailProtocol("smtp");// 发送邮件协议名称 myEmail.setSubject("这是主题!!!"); //创建一个线程池 ExecutorService pool = Executors.newFixedThreadPool(1); //创建1个有返回值的任务 SendEmailCallable sendEmailCallable = new SendEmailCallable(myEmail, new SendMail()); // 提交并执行任务,任务启动时返回了一个Future对象, // 如果想得到任务执行的结果或者是异常可对这个Future对象进行操作 Future future = pool.submit(sendEmailCallable); //从Future对象上获取任务的返回值,并输出到控制台 System.out.println(future.get().toString());//Future的 get 方法等待计算完成,获取计算结果 //关闭线程池 pool.shutdown(); ; } } class SendMail implements SendEmail{ public String getId() { return UUID.getUUID(); } public String getToken() { return PasswordUtil.getToken(getName(),getId()); } public String getName() { return "chenhaoxiang"; } public String getEmail() { return TestMail.mail; } }
#收到邮件后的效果: