因为Java在开发网页上占有绝大优势。所以作为web端的领军人物,譬如发送短信和发送邮件这些就成了必定,网络安全一再安全我们须要把账号的安全级别提到更高。因此这些对于开发者也就成了必须掌握的技能!我一直都认为作为开发者,不怕在开发的过程中遇到多少难题,而是有没有去解决它的勇气和决心,这里多学习就成为了关键,成为了一个程序员发展的重中之重!好啦。闲话就讲到这里。来点实际的。
当一个开发者工作到一定程度后,面向对象的思维就会一直在他的老子里环绕。所以我们先把邮件的常量类、实体类以及工具类等等先该封装的封装,该继承的继承!代码来了。睁大眼睛:
/** * @Description: * * @Title: SimpleMail.java * @Package com.joyce.bean * @Copyright: Copyright (c) 2014 * * @author Comsys-LZP * @date 2014-5-28 上午09:06:51 * @version V2.0 */ package com.joyce.mail.bean; /** * @Description:邮件信息类 * * @ClassName: SimpleMail * @Copyright: Copyright (c) 2014 * * @author Comsys-LZP * @date 2014-5-28 上午09:06:51 * @version V2.0 */ public class Mail { /** * 主题 */ private String subject; /** * 内容 */ private String content; /** * @return the subject */ public String getSubject() { return subject; } /** * @param subject * the subject to set */ public void setSubject(String subject) { this.subject = subject; } /** * @return the content */ public String getContent() { return content; } /** * @param content * the content to set */ public void setContent(String content) { this.content = content; } }
上面大家看到的就是发送邮件一般不可缺少的邮件标题和邮件内容,作为在邮件使用广泛的那就免不了封装起来了,好啦。接下来咱们看邮箱的登录类:
/** * @Description: * * @Title: MailAuthenticator.java * @Package com.joyce.bean * @Copyright: Copyright (c) 2014 * * @author Comsys-LZP * @date 2014-5-28 上午08:59:11 * @version V2.0 */ package com.joyce.mail.bean; import javax.mail.Authenticator; import javax.mail.PasswordAuthentication; /** * @Description: 邮箱登录类 * * @ClassName: MailAuthenticator * @Copyright: Copyright (c) 2014 * * @author Comsys-LZP * @date 2014-5-28 上午08:59:11 * @version V2.0 */ public class MailAuthenticator extends Authenticator { /** * 用户名(登录邮箱) */ private String username; /** * 密码 */ private String password; /** * @return the username */ public String getUsername() { return username; } /** * @param username the username to set */ public void setUsername(String username) { this.username = username; } /** * @return the password */ public String getPassword() { return password; } /** * @param password the password to set */ public void setPassword(String password) { this.password = password; } /** * @param username * @param password */ public MailAuthenticator(String username, String password) { this.username = username; this.password = password; } @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }
这时候我们须要的常量类就应该进来了
package com.joyce.mail.bean; import java.text.SimpleDateFormat; import java.util.Date; /** * @Description: 邮件发送常量类 * * @ClassName: MailConstant * @Copyright: Copyright (c) 2014 * * @author Comsys-LZP * @date 2014-5-28 上午11:01:16 * @version V2.0 */ public class MailConstant { public static final String MAIL_USER = "luo201227@163.com"; public static final String MAIL_PWD = "*****"; public static final boolean MAIL_IFDEBUG = true; public static final String MAIL_CONTENT_CHARSET = "text/html;charset=utf-8"; public static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒 E"); public static final String MAIL_TITLE = "*********账号激活码" + sdf.format(new Date());//邮件标题 public static String getMailContent(String content){ StringBuffer sb = new StringBuffer(); sb.append("<div style='1024px;height:auto;margin:0px auto;background-color:#66CCFF;font-size:14px;font-family:微软雅黑;border-radius:5px;padding:5px;'><center><h1>"); sb.append("</h1></center><div style='margin-left:20px;margin-bottom:10px;'><b>尊敬的用户。您好!</b><br/><br/>"); sb.append(" <b></b>"+content); sb.append("</div></div>"); return sb.toString(); } }
关键来了,看看发送邮件的关键部分吧
/** * @Description: * * @Title: MailSender.java * @Package com.joyce.service.impl * @Copyright: Copyright (c) 2014 * * @author Comsys-LZP * @date 2014-5-28 上午09:03:08 * @version V2.0 */ package com.hupu.nac.mail.sender; import java.io.File; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Properties; import java.util.Vector; import javax.activation.DataHandler; import javax.activation.FileDataSource; import javax.mail.BodyPart; import javax.mail.Message; import javax.mail.MessagingException; 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; import com.hupu.nac.mail.bean.Mail; import com.hupu.nac.mail.bean.MailAuthenticator; import com.hupu.nac.mail.bean.MailConstant; /** * @Description:邮件发送类 * * @ClassName: MailSender * @Copyright: Copyright (c) 2014 * * @author Comsys-LZP * @date 2014-5-28 上午09:03:08 * @version V2.0 */ public class MailSender { /** * 发送邮件的props文件 */ private final transient Properties props = new Properties(); /** * 邮件server登录验证 */ private transient MailAuthenticator authenticator; /** * 邮箱session */ private transient Session session; /** * 初始化邮件发送器 * * @param smtpHostName * SMTP邮件server地址 * @param username * 发送邮件的用户名(地址) * @param password * 发送邮件的密码 */ public MailSender(final String smtpHostName, final String username, final String password) { init(username, password, smtpHostName); } /** * 初始化邮件发送器 * * @param username * 发送邮件的用户名(地址),并以此解析SMTPserver地址 * @param password * 发送邮件的密码 */ public MailSender(final String username, final String password) { // 通过邮箱地址解析出smtpserver。对大多数邮箱都管用 final String smtpHostName = "smtp." + username.split("@")[1]; init(username, password, smtpHostName); } /** * @Description: 初始化 * * @param username * 发送邮件的用户名(地址) * @param password * 密码 * @param smtpHostName * SMTP主机地址 * * @Title: MailSender.java * @Copyright: Copyright (c) 2014 * * @author Comsys-LZP * @date 2014-5-28 上午09:18:31 * @version V2.0 */ private void init(String username, String password, String smtpHostName) { // 初始化props props.put("mail.smtp.host", smtpHostName); props.put("mail.smtp.auth", "true"); // 验证 authenticator = new MailAuthenticator(username, password); // 创建session session = Session.getInstance(props, authenticator); // 打印一些调试信息 session.setDebug(MailConstant.MAIL_IFDEBUG); } /** * @Description: 发送邮件 * * @param recipient * 收件人邮箱地址 * @param subject * 邮件主题 * @param content * 邮件内容 * @throws AddressException * @throws MessagingException * * @Title: MailSender.java * @Copyright: Copyright (c) 2014 * * @author Comsys-LZP * @date 2014-5-28 上午09:19:16 * @version V2.0 */ public void send(String recipient, String subject, Object content) throws Exception { send(recipient, subject, content, null); } /** * 发送邮件 * * @param recipient * 收件人邮箱地址 * @param subject * 邮件主题 * @param content * 邮件内容 * @param files * 附件 * @throws Exception * @author Joyce.Luo * @date 2014-10-15 上午10:23:09 * @version V3.0 * @since Tomcat6.0,Jdk1.6 * @copyright: Copyright (c) 2014 */ public void send(String recipient, String subject, Object content, Vector<File> files) throws Exception { // 创建mime类型邮件 final MimeMessage message = new MimeMessage(session); // 设置发信人 message.setFrom(new InternetAddress(authenticator.getUsername())); // 设置收件人 message.setRecipient(Message.RecipientType.TO, new InternetAddress( recipient)); // 设置主题 message.setSubject(subject); // 设置邮件内容 if (null == files || files.size() == 0) { message.setContent(content.toString(), MailConstant.MAIL_CONTENT_CHARSET); } else { //创建 Mimemultipart加入内容(可包括多个附件) MimeMultipart multipart = new MimeMultipart(); //MimeBodyPart(用于信件内容/附件) BodyPart bodyPart = new MimeBodyPart(); bodyPart.setContent(content.toString(), MailConstant.MAIL_CONTENT_CHARSET); //加入到MimeMultipart对象中 multipart.addBodyPart(bodyPart); for (int i = 0; i < files.size(); i++) { File file = (File) files.elementAt(i); String fname = file.getName(); //创建FileDAtaSource(用于加入附件) FileDataSource fds = new FileDataSource(file); BodyPart fileBodyPart = new MimeBodyPart(); // 字符流形式装入文件 fileBodyPart.setDataHandler(new DataHandler(fds)); // 设置附件文件名称 fileBodyPart.setFileName(fname); multipart.addBodyPart(fileBodyPart); message.setContent(multipart); } } // 设置发信时间 message.setSentDate(new Date()); // 存储邮件信息 message.saveChanges(); // message.setFileName(filename) // 发送邮件 Transport.send(message); } /** * @Description: 群发邮件 * * @param recipients * 收件人们 * @param subject * 主题 * @param content * 内容 * @throws AddressException * @throws MessagingException * * @Title: MailSender.java * @Copyright: Copyright (c) 2014 * * @author Comsys-LZP * @date 2014-5-28 上午09:20:24 * @version V2.0 */ public void send(List<String> recipients, String subject, Object content) throws Exception { send(recipients, subject, content, null); } /** * 群发邮件 * * @param recipients * 收件人们 * @param subject * 主题 * @param content * 内容 * @param files * 附件 * @throws Exception * @author Joyce.Luo * @date 2014-10-15 上午10:26:35 * @version V3.0 * @since Tomcat6.0,Jdk1.6 * @copyright: Copyright (c) 2014 */ public void send(List<String> recipients, String subject, Object content, Vector<File> files) throws Exception { // 创建mime类型邮件 final MimeMessage message = new MimeMessage(session); // 设置发信人 message.setFrom(new InternetAddress(authenticator.getUsername())); // 设置收件人们 final int num = recipients.size(); InternetAddress[] addresses = new InternetAddress[num]; for (int i = 0; i < num; i++) { addresses[i] = new InternetAddress(recipients.get(i)); } message.setRecipients(Message.RecipientType.TO, addresses); // 设置主题 message.setSubject(subject); // 设置邮件内容 if (null == files || files.size() == 0) { message.setContent(content.toString(), MailConstant.MAIL_CONTENT_CHARSET); } else { //创建 Mimemultipart加入内容(可包括多个附件) MimeMultipart multipart = new MimeMultipart(); //MimeBodyPart(用于信件内容/附件) BodyPart bodyPart = new MimeBodyPart(); bodyPart.setContent(content.toString(), MailConstant.MAIL_CONTENT_CHARSET); //加入到MimeMultipart对象中 multipart.addBodyPart(bodyPart); for (int i = 0; i < files.size(); i++) { File file = (File) files.elementAt(i); String fname = file.getName(); //创建FileDAtaSource(用于加入附件) FileDataSource fds = new FileDataSource(file); BodyPart fileBodyPart = new MimeBodyPart(); // 字符流形式装入文件 fileBodyPart.setDataHandler(new DataHandler(fds)); // 设置附件文件名称 fname = new String(fname.getBytes("UTF-8"), "ISO-8859-1"); fileBodyPart.setFileName(fname); multipart.addBodyPart(fileBodyPart); message.setContent(multipart); } } // 设置发信时间 message.setSentDate(new Date()); // 存储邮件信息 message.saveChanges(); // 发送邮件 Transport.send(message); } /** * @Description: 发送邮件 * * @param recipient * 收件人邮箱地址 * @param mail * 邮件对象 * @throws Exception * * @Title: MailSender.java * @Copyright: Copyright (c) 2014 * * @author Comsys-LZP * @date 2014-5-28 上午09:20:54 * @version V2.0 */ public void send(String recipient, Mail mail) throws Exception { send(recipient, mail.getSubject(), mail.getContent()); } /** * @Description: 群发邮件 * * @param recipients * 收件人们 * @param mail * 邮件对象 * @throws Exception * * @Title: MailSender.java * @Copyright: Copyright (c) 2014 * * @author Comsys-LZP * @date 2014-5-28 上午09:21:19 * @version V2.0 */ public void send(List<String> recipients, Mail mail) throws Exception { send(recipients, mail.getSubject(), mail.getContent()); } /** * 群发邮件 * * @param recipients * 收件人们 * @param mail * 邮件对象 * @param files * 附件 * @throws Exception * @author Joyce.Luo * @date 2014-10-15 上午10:28:38 * @version V3.0 * @since Tomcat6.0,Jdk1.6 * @copyright: Copyright (c) 2014 */ public void send(List<String> recipients, Mail mail, Vector<File> files) throws Exception { send(recipients, mail.getSubject(), mail.getContent(), files); } }
在网页上的激活码或者验证码这类的就不用多说了吧
/** * @Description: * * @Title: RandomCodeUtil.java * @Package com.joyce.mail.util * @Copyright: Copyright (c) 2014 * * @author Comsys-LZP * @date 2014-5-28 上午11:07:34 * @version V2.0 */ package com.joyce.mail.util; /** * @Description: 随机码工具类 * * @ClassName: RandomCodeUtil * @Copyright: Copyright (c) 2014 * * @author Comsys-LZP * @date 2014-5-28 上午11:07:34 * @version V2.0 */ public class RandomCodeUtil { /** * 随机码集合 */ private static final String[] randCode = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "q", "w", "e", "r", "t", "y", "u", "i", "o", "p", "a", "s", "d", "f", "g", "h", "j", "k", "l", "z", "x", "c", "v", "b", "n", "m" }; /** * @Description: 产生指定长度的随机码 * * @param codeLength * @return * * @Title: RandomCodeUtil.java * @Copyright: Copyright (c) 2014 * * @author Comsys-LZP * @date 2014-5-28 上午11:11:55 * @version V2.0 */ public static String randomCode(Integer codeLength) throws Exception { try { StringBuffer code = new StringBuffer(); if(null == codeLength || 0 == codeLength){ codeLength = 4; } for (int i = 0; i < codeLength; i++) { code.append(randCode[(int)Math.floor(Math.random() * 36)]); } return code.toString(); } catch (Exception e) { throw new RuntimeException("Random Code Error"); } } /** * @Description: 生成长度为4的随机码 * * @return * @throws Exception * * @Title: RandomCodeUtil.java * @Copyright: Copyright (c) 2014 * * @author Comsys-LZP * @date 2014-5-28 下午01:19:33 * @version V2.0 */ public static String randomCode() throws Exception{ return randomCode(null); } }
Ok。利用javax.mail.jar发送邮件就大功告成了!是不是非常easy呢。完整的demo资源;下载地址:http://download.csdn.net/download/luo201227/7446279
有段时间了。来更新一下。事实上也没有什么非常多要说的,仅仅是跟大家提一下。假设有兴趣的,能够去了解一下James邮件server的搭建!