今天闲着无事,研究了一下javaMail发送电子邮件的方法,自己总结了个步骤:
1、首先需要获取发送邮件的Session对象
Session session = Session.getDefaultInstance(properties,authorcator);
2、根据session对象,获取待发送的邮件消息
MimeMessage mimeMessage = new MimeMessage(session);
3、设置发件人,收件人,标题,邮件内容,附件,发送时间等;
4、利用Transport发送邮件
以下是居然的实现代码:
1、邮件信息类:
package com.china.test.mail; import java.util.Properties; /** * 发送邮件需要使用的基本信息 * @author dove * */ public class MailSenderInfo { // 发送邮件的服务器的IP private String mailServerHost; // 发送邮件的服务器的端口 private String mailServerPort = "25"; // 邮件发送者的地址 private String fromAddress; // 邮件接收者的地址 private String[] toAddress; // 邮件密送接收者的地址 private String[] toBlindCarbonCopyAddress; // 邮件抄送接收者的地址 private String[] toCarbonCopyAddress; // 登陆邮件发送服务器的用户名 private String userName; // 登陆邮件发送服务器的密码 private String password; // 是否需要身份验证 private boolean validate = false; // 邮件主题 private String subject; // 邮件的文本内容 private String content; // 邮件附件的文件名 private String[] attachFileNames; /** * 获得邮件会话属性 */ public Properties getProperties() { Properties pro = new Properties(); pro.put("mail.smtp.host", this.mailServerHost); pro.put("mail.smtp.port", this.mailServerPort); pro.put("mail.smtp.auth", validate ? "true" : "false"); return pro; } 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 String getFromAddress() { return fromAddress; } public void setFromAddress(String fromAddress) { this.fromAddress = fromAddress; } 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 getPassword() { return password; } public void setPassword(String password) { this.password = password; } public boolean isValidate() { return validate; } public void setValidate(boolean validate) { this.validate = validate; } public String getSubject() { return subject; } public void setSubject(String subject) { this.subject = subject; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String[] getAttachFileNames() { return attachFileNames; } public void setAttachFileNames(String[] attachFileNames) { this.attachFileNames = attachFileNames; } public String[] getToBlindCarbonCopyAddress() { return toBlindCarbonCopyAddress; } public void setToBlindCarbonCopyAddress(String[] toBlindCarbonCopyAddress) { this.toBlindCarbonCopyAddress = toBlindCarbonCopyAddress; } public String[] getToCarbonCopyAddress() { return toCarbonCopyAddress; } public void setToCarbonCopyAddress(String[] toCarbonCopyAddress) { this.toCarbonCopyAddress = toCarbonCopyAddress; } }
2、身份验证类
package com.china.test.mail; import javax.mail.Authenticator; import javax.mail.PasswordAuthentication; /** * 身份验证器 * @author dove * */ public class MyAuthenticator extends Authenticator { private String username; private String password; public MyAuthenticator(){ } public MyAuthenticator(String username, String password) { this.username = username; this.password = password; } @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
3、发送邮件类
该类有两个功能,一个是发送普通文本邮件;一个是发送html邮件,两者的本质是相同的,mime类型有所区别而已,具体请看代码:
package com.china.test.mail; import java.io.UnsupportedEncodingException; import java.util.Date; import java.util.Properties; import javax.activation.DataHandler; import javax.activation.DataSource; import javax.activation.FileDataSource; 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; import javax.mail.internet.MimeUtility; /** * 简单邮件发送器 * @author dove * */ public class SimpleMailSender { /** * 以文本格式发送邮件 (支持群发,带附件) * @param senderInfo 待发送的邮件的信息 * @return */ public static boolean sendMail(MailSenderInfo senderInfo){ boolean flag = false; // 判断是否需要身份验证 MyAuthenticator authenticator = null; Properties props = senderInfo.getProperties(); if(senderInfo.isValidate()){ // 如果需要身份认证,则创建一个密码验证器 authenticator = new MyAuthenticator(senderInfo.getUserName(), senderInfo.getPassword()); } // 根据邮件会话属性和密码验证器构造一个发送邮件的session Session sendMailSession = Session.getDefaultInstance(props, authenticator); try { // 根据session创建一个邮件消息 Message sendMailMessage = new MimeMessage(sendMailSession); // 创建邮件发送者地址 Address from = new InternetAddress(senderInfo.getFromAddress()); // 设置邮件消息的发送者 sendMailMessage.setFrom(from); // 创建邮件接收者地址 String[] tos = senderInfo.getToAddress(); if(tos != null && tos.length != 0){ InternetAddress[] to = new InternetAddress[tos.length]; // 设置邮件消息的发送者 for (int i = 0; i < tos.length; i++) { to[i] = new InternetAddress(tos[i]); } sendMailMessage.setRecipients(Message.RecipientType.TO, to); } // 设置邮件抄送者地址 String[] toCCs = senderInfo.getToCarbonCopyAddress(); if(toCCs != null && toCCs.length != 0){ InternetAddress[] toCC = new InternetAddress[toCCs.length]; // 设置邮件消息的发送者 for (int i = 0; i < toCCs.length; i++) { toCC[i] = new InternetAddress(toCCs[i]); } sendMailMessage.addRecipients(Message.RecipientType.CC, toCC); } // 设置邮件密送者地址 String[] toBCCs = senderInfo.getToBlindCarbonCopyAddress(); if(toBCCs != null && toBCCs.length != 0){ InternetAddress[] toBCC = new InternetAddress[toBCCs.length]; for (int i = 0; i < toBCCs.length; i++) { toBCC[i] = new InternetAddress(toBCCs[i]); } sendMailMessage.addRecipients(Message.RecipientType.BCC, toBCC); } // 设置邮件主题 sendMailMessage.setSubject(MimeUtility.encodeText(senderInfo.getSubject(),"utf-8","B")); // 设置邮件内容 //sendMailMessage.setText(senderInfo.getContent()); Multipart multipart = new MimeMultipart(); // 邮件文本内容 if(senderInfo.getContent() != null && !"".equals(senderInfo.getContent())){ BodyPart part = new MimeBodyPart(); part.setContent(senderInfo.getContent(), "text/plain;charset=utf-8");//设置邮件文本内容 multipart.addBodyPart(part); } // 附件 String attachFileNames[] = senderInfo.getAttachFileNames(); int leng = attachFileNames == null ? 0 : attachFileNames.length; for (int i = 0; i < leng; i++) { BodyPart part = new MimeBodyPart(); // 根据文件名获取数据源 DataSource dataSource = new FileDataSource(attachFileNames[i]); DataHandler dataHandler = new DataHandler(dataSource); // 得到附件本身并至入BodyPart part.setDataHandler(dataHandler); // 得到文件名同样至入BodyPart part.setFileName(MimeUtility.encodeText(dataSource.getName())); multipart.addBodyPart(part); } sendMailMessage.setContent(multipart); // 设置邮件发送的时间 sendMailMessage.setSentDate(new Date()); // 发送邮件 //Transport.send(sendMailMessage); Transport transport = sendMailSession.getTransport("smtp"); transport.connect(senderInfo.getUserName(), senderInfo.getPassword()); transport.send(sendMailMessage,sendMailMessage.getAllRecipients()); transport.close(); flag = true; } catch (AddressException e) { e.printStackTrace(); } catch (MessagingException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return flag; } public static boolean sendHtmlMail(MailSenderInfo senderInfo){ boolean flag = false; // 判断是否需要身份验证 MyAuthenticator authenticator = null; Properties props = senderInfo.getProperties(); if(senderInfo.isValidate()){ // 如果需要身份认证,则创建一个密码验证器 authenticator = new MyAuthenticator(senderInfo.getUserName(), senderInfo.getPassword()); } // 根据邮件会话属性和密码验证器构造一个发送邮件的session Session sendMailSession = Session.getDefaultInstance(props, authenticator); try { // 根据session创建一个邮件消息 Message sendMailMessage = new MimeMessage(sendMailSession); // 创建邮件发送者地址 Address from = new InternetAddress(senderInfo.getFromAddress()); // 设置邮件消息的发送者 sendMailMessage.setFrom(from); // 创建邮件接收者地址 String[] tos = senderInfo.getToAddress(); if(tos != null && tos.length != 0){ InternetAddress[] to = new InternetAddress[tos.length]; // 设置邮件消息的发送者 for (int i = 0; i < tos.length; i++) { to[i] = new InternetAddress(tos[i]); } sendMailMessage.setRecipients(Message.RecipientType.TO, to); } // 设置邮件抄送者地址 String[] toCCs = senderInfo.getToCarbonCopyAddress(); if(toCCs != null && toCCs.length != 0){ InternetAddress[] toCC = new InternetAddress[toCCs.length]; // 设置邮件消息的发送者 for (int i = 0; i < toCCs.length; i++) { toCC[i] = new InternetAddress(toCCs[i]); } sendMailMessage.addRecipients(Message.RecipientType.CC, toCC); } // 设置邮件密送者地址 String[] toBCCs = senderInfo.getToBlindCarbonCopyAddress(); if(toBCCs != null && toBCCs.length != 0){ InternetAddress[] toBCC = new InternetAddress[toBCCs.length]; for (int i = 0; i < toBCCs.length; i++) { toBCC[i] = new InternetAddress(toBCCs[i]); } sendMailMessage.addRecipients(Message.RecipientType.BCC, toBCC); } // 设置邮件主题 sendMailMessage.setSubject(MimeUtility.encodeText(senderInfo.getSubject(),"utf-8","B")); // 设置邮件内容 //sendMailMessage.setText(senderInfo.getContent()); Multipart multipart = new MimeMultipart(); // 邮件文本内容 if(senderInfo.getContent() != null && !"".equals(senderInfo.getContent())){ BodyPart part = new MimeBodyPart(); part.setContent(senderInfo.getContent(), "text/html;charset=utf-8");//设置邮件文本内容 multipart.addBodyPart(part); } // 附件 String attachFileNames[] = senderInfo.getAttachFileNames(); int leng = attachFileNames == null ? 0 : attachFileNames.length; for (int i = 0; i < leng; i++) { BodyPart part = new MimeBodyPart(); // 根据文件名获取数据源 DataSource dataSource = new FileDataSource(attachFileNames[i]); DataHandler dataHandler = new DataHandler(dataSource); // 得到附件本身并至入BodyPart part.setDataHandler(dataHandler); // 得到文件名同样至入BodyPart part.setFileName(MimeUtility.encodeText(dataSource.getName())); multipart.addBodyPart(part); } sendMailMessage.setContent(multipart); // 设置邮件发送的时间 sendMailMessage.setSentDate(new Date()); // 发送邮件 //Transport.send(sendMailMessage); Transport transport = sendMailSession.getTransport("smtp"); transport.connect(senderInfo.getUserName(), senderInfo.getPassword()); transport.send(sendMailMessage,sendMailMessage.getAllRecipients()); // 关闭transport transport.close(); flag = true; } catch (AddressException e) { e.printStackTrace(); } catch (MessagingException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return flag; } public static void main(String[] args) { MailSenderInfo mailInfo = new MailSenderInfo(); mailInfo.setMailServerHost("smtp.sina.com"); mailInfo.setMailServerPort("25"); mailInfo.setValidate(true); mailInfo.setUserName("********@sina.com"); mailInfo.setPassword("*********");// 您的邮箱密码 mailInfo.setFromAddress("[email protected]"); String[] to = {"********@bj.china.com"}; mailInfo.setToAddress(to); String[] toCC = {"**********@qq.com"}; mailInfo.setToCarbonCopyAddress(toCC); String[] toBCC = {"*******@sina.com"}; mailInfo.setToBlindCarbonCopyAddress(toBCC); mailInfo.setAttachFileNames(new String[]{"C:/Documents and Settings/Administrator/桌面/考勤休假制度表格(新).xls","C:/Documents and Settings/Administrator/桌面/dove.jpg"}); mailInfo.setSubject("发送HTML邮件"); String body = "
你好 | 你好 | 你好 |
本代码必须依赖与mail.jar 包,请自行下载。