由于Java在开发网页上占有绝大优势,所以作为web端的领军人物,譬如发送短信和发送邮件这些就成了必然,网络安全一再安全我们需要把账号的安全级别提到更高!因此这些对于开发人员也就成了必须掌握的技能!我一直都觉得作为开发人员,不怕在开发的过程中遇到多少难题,而是有没有去解决它的勇气和决心,这里多学习就成为了关键,成为了一个程序猿发展的重中之重!好啦,闲话就说到这里,来点实际的!
当一个开发人员工作到一定程度后,面向对象的思维就会一直在他的老子里围绕!所以我们先把邮件的常量类、实体类以及工具类等等先该封装的封装,该继承的继承!代码来了,睁大眼睛:
/*** @Description: ** @Title: SimpleMail.java* @Package com.joyce.bean* @Copyright: Copyright (c) ** @author Comsys-LZP* @date -5-28 上午09:06:51* @version V2.0*/package com.joyce.mail.bean;/*** @Description:邮件信息类* * @ClassName: SimpleMail* @Copyright: Copyright (c) * * @author Comsys-LZP* @date -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) ** @author Comsys-LZP* @date -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) ** @author Comsys-LZP* @date -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;}@Overrideprotected 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) ** @author Comsys-LZP* @date -5-28 上午11:01:16* @version V2.0*/public class MailConstant {public static final String MAIL_USER = "luo27@"; 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='width: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) ** @author Comsys-LZP* @date -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) * * @author Comsys-LZP* @date -5-28 上午09:03:08* @version V2.0*/public class MailSender {/*** 发送邮件的props文件*/private final transient Properties props = new Properties();/*** 邮件服务器登录验证*/private transient MailAuthenticator authenticator;/*** 邮箱session*/private transient Session session;/*** 初始化邮件发送器* * @param smtpHostName* SMTP邮件服务器地址* @param username* 发送邮件的用户名(地址)* @param password* 发送邮件的密码*/public MailSender(final String smtpHostName, final String username,final String password) {init(username, password, smtpHostName);}/*** 初始化邮件发送器* * @param username* 发送邮件的用户名(地址),并以此解析SMTP服务器地址* @param password* 发送邮件的密码*/public MailSender(final String username, final String password) {// 通过邮箱地址解析出smtp服务器,对大多数邮箱都管用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) * * @author Comsys-LZP* @date -5-28 上午09:18:31* @version V2.0*/private void init(String username, String password, String smtpHostName) {// 初始化propsprops.put("mail.smtp.host", smtpHostName);props.put("mail.smtp.auth", "true");// 验证authenticator = new MailAuthenticator(username, password);// 创建sessionsession = 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) * * @author Comsys-LZP* @date -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 -10-15 上午10:23:09* @version V3.0* @since Tomcat6.0,Jdk1.6* @copyright: Copyright (c) */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) * * @author Comsys-LZP* @date -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 -10-15 上午10:26:35* @version V3.0* @since Tomcat6.0,Jdk1.6* @copyright: Copyright (c) */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) * * @author Comsys-LZP* @date -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) * * @author Comsys-LZP* @date -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 -10-15 上午10:28:38* @version V3.0* @since Tomcat6.0,Jdk1.6* @copyright: Copyright (c) */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) ** @author Comsys-LZP* @date -5-28 上午11:07:34* @version V2.0*/package com.joyce.mail.util;/*** @Description: 随机码工具类* * @ClassName: RandomCodeUtil* @Copyright: Copyright (c) * * @author Comsys-LZP* @date -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) ** @author Comsys-LZP* @date -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) ** @author Comsys-LZP* @date -5-28 下午01:19:33* @version V2.0*/public static String randomCode() throws Exception{return randomCode(null);}}
Ok,利用javax.mail.jar发送邮件就大功告成了!是不是很easy呢!
有段时间了,来更新一下,其实也没有什么很多要说的,只是跟大家提一下,如果有兴趣的,可以去了解一下James邮件服务器的搭建!
如果觉得《Java使用javax.mail.jar发送邮件并允许发送附件》对你有帮助,请点赞、收藏,并留下你的观点哦!