转载请注明出处:http://blog.csdn.net/l1028386804/article/details/51146788
今天,给大家具体讲讲如何利用java mail实现发送邮箱的功能,不多说了,我们直接进入主题。
java发送邮件需要3个jar包的支持,分别是activation.jar,additionnal.jar,mail.jar,大家可以到链接http://download.csdn.net/detail/l1028386804/9490320下载这些所需的jar包,将这些jar包放入到自己的java工程中。
这个类是发送邮件的基本信息类,存储了发送邮件的各种信息,包括发送邮件的服务器地址、端口,发送者的邮箱、账号、密码、接收者的邮箱和邮件内容等信息。
具体代码如下:
package com.lyz.utils.email; import java.util.Properties; /** * 邮件发送信息类 * @author liuyazhuang * */ public class MailSenderInfo { // 发送邮件的服务器的IP和端口 private String mailServerHost; private String mailServerPort = "25"; // 邮件发送者的地址 private String fromAddress; // 邮件接收者的地址 private String toAddress; // 登陆邮件发送服务器的用户名和密码 private String userName; private String password; // 是否需要身份验证 private boolean validate = true; // 邮件主题 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"); p.put("mail.smtp.socketFactory.port", "465"); p.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory"); p.put("mail.smtp.socketFactory.fallback", "false"); p.setProperty("mail.smtp.quitwait", "false"); return p; } public MailSenderInfo() { super(); } public MailSenderInfo(String mailServerHost, String mailServerPort, String fromAddress, String toAddress, String userName, String password, boolean validate, String subject, String content) { super(); this.mailServerHost = mailServerHost; this.mailServerPort = mailServerPort; this.fromAddress = fromAddress; this.toAddress = toAddress; this.userName = userName; this.password = password; this.validate = validate; this.subject = subject; this.content = content; } 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; } }
这个类是发送邮件时的认证类,此类继承自Authenticator。
具体代码如下:
package com.lyz.utils.email; import javax.mail.Authenticator; import javax.mail.PasswordAuthentication; /** * 发送邮件的认证类 * @author liuyazhuang * */ 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); } }
这个类是整个项目的核心,是整个项目的邮件发送器。这个类共实现了4个方法:
(1)以文本格式发送邮件,不带附件的sendTextMail方法;
(2)以带附件的方式发送文本格式邮件的sendTextMailWithAttachment方法
(3)以HTML格式发送邮件,带附件的sendHtmlMailWithAttachment方法
(4)以HTML格式发送邮件,不带附件的sendHtmlMail方法
具体代码如下:
package com.lyz.utils.email; import java.util.Date; import java.util.Properties; import javax.activation.CommandMap; import javax.activation.DataHandler; import javax.activation.FileDataSource; import javax.activation.MailcapCommandMap; 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.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; /** * @author liuyazhuang * 邮件发送器 */ public class MailSender { /** * 以文本格式发送邮件,不带附件 * @param mailInfo * 待发送的邮件的信息 */ public static 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); // 创建邮件的接收者地址,并设置到邮件消息中 Address to = new InternetAddress(mailInfo.getToAddress()); mailMessage.setRecipient(Message.RecipientType.TO, to); // 设置邮件消息的主题 mailMessage.setSubject(mailInfo.getSubject()); // 设置邮件消息发送的时间 mailMessage.setSentDate(new Date()); // 设置邮件消息的主要内容 String mailContent = mailInfo.getContent(); mailMessage.setText(mailContent); MailcapCommandMap mc = (MailcapCommandMap) CommandMap.getDefaultCommandMap(); mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html"); mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml"); mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain"); mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed"); mc.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822"); CommandMap.setDefaultCommandMap(mc); // 发送邮件 Transport.send(mailMessage); return true; } catch (MessagingException ex) { ex.printStackTrace(); } return false; } /** * 以带附件的方式发送文本格式邮件 * @param mailInfo 待发送的邮件的信息 * @param filenames 附件的磁盘绝对路径 */ public static boolean sendTextMailWithAttachment(MailSenderInfo mailInfo, String ... filenames) { // 判断是否需要身份认证 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); // 创建邮件的接收者地址,并设置到邮件消息中 Address to = new InternetAddress(mailInfo.getToAddress()); mailMessage.setRecipient(Message.RecipientType.TO, to); // 设置邮件消息的主题 mailMessage.setSubject(mailInfo.getSubject()); // 设置邮件消息发送的时间 mailMessage.setSentDate(new Date()); //实例化Multipart Multipart mp = new MimeMultipart(); //实例化发送文本的MimeBodyPart MimeBodyPart textFile = new MimeBodyPart(); //设置文本信息 textFile.setText(mailInfo.getContent(), "UTF-8"); mp.addBodyPart(textFile); //是否添加了附件 if(filenames != null && filenames.length > 0){ for(int i = 0; i < filenames.length; i++){ String fileName = filenames[i]; //文件名为空,跳过本次循环 if(fileName == null || "".equals(fileName.trim())){ continue; } MimeBodyPart mbpFile = new MimeBodyPart(); FileDataSource fds = new FileDataSource(fileName); mbpFile.setDataHandler(new DataHandler(fds)); mbpFile.setFileName(fileName); mp.addBodyPart(mbpFile); } } mailMessage.setContent(mp); MailcapCommandMap mc = (MailcapCommandMap) CommandMap.getDefaultCommandMap(); mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html"); mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml"); mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain"); mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed"); mc.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822"); CommandMap.setDefaultCommandMap(mc); // 发送邮件 Transport.send(mailMessage); return true; } catch (MessagingException ex) { ex.printStackTrace(); } return false; } /** * 以HTML格式发送邮件,带附件 * @param mailInfo * 待发送的邮件信息 * @param filenames:附件在磁盘上的绝对路径 */ public static boolean sendHtmlMailWithAttachment(MailSenderInfo mailInfo, String... filenames) { // 判断是否需要身份认证 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); // 创建邮件的接收者地址,并设置到邮件消息中 Address to = new InternetAddress(mailInfo.getToAddress()); // Message.RecipientType.TO属性表示接收者的类型为TO mailMessage.setRecipient(Message.RecipientType.TO, to); // 设置邮件消息的主题 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); //是否添加了附件 if(filenames != null && filenames.length > 0){ for(int i = 0; i < filenames.length; i++){ String fileName = filenames[i]; //文件名为空,跳过本次循环 if(fileName == null || "".equals(fileName.trim())){ continue; } MimeBodyPart mbpFile = new MimeBodyPart(); FileDataSource fds = new FileDataSource(fileName); mbpFile.setDataHandler(new DataHandler(fds)); mbpFile.setFileName(fileName); mainPart.addBodyPart(mbpFile); } } // 将MiniMultipart对象设置为邮件内容 mailMessage.setContent(mainPart); MailcapCommandMap mc = (MailcapCommandMap) CommandMap.getDefaultCommandMap(); mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html"); mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml"); mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain"); mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed"); mc.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822"); CommandMap.setDefaultCommandMap(mc); // 发送邮件 Transport.send(mailMessage); return true; } catch (MessagingException ex) { ex.printStackTrace(); } return false; } /** * 以HTML格式发送邮件 * @param mailInfo * 待发送的邮件信息 */ 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); // 创建邮件的接收者地址,并设置到邮件消息中 Address to = new InternetAddress(mailInfo.getToAddress()); // Message.RecipientType.TO属性表示接收者的类型为TO mailMessage.setRecipient(Message.RecipientType.TO, to); // 设置邮件消息的主题 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); MailcapCommandMap mc = (MailcapCommandMap) CommandMap.getDefaultCommandMap(); mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html"); mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml"); mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain"); mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed"); mc.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822"); CommandMap.setDefaultCommandMap(mc); // 发送邮件 Transport.send(mailMessage); return true; } catch (MessagingException ex) { ex.printStackTrace(); } return false; } }
为了更加符合编程的规范,这里我们将发送邮件必须要用到的一些信息放到一个配置文件中,在项目的classpath目录下建立email.properties文件。
具体代码如下:
mail_server_host = smtp.qq.com mail_server_port = 995 mail_user_name = your username mail_password = your password mail_from_address = your email where send email注:大家要将文件中的用户名、密码、和发送邮件的邮箱替换为自己的用户名、密码和发送邮件的邮箱。
这个类是整个项目的测试类,测试是否能够实现发送邮件的功能
具体代码如下:
package com.lyz.utils.test; import java.io.InputStream; import java.util.Properties; import com.lyz.utils.email.MailSender; import com.lyz.utils.email.MailSenderInfo; /** * 测试发送邮件 * @author liuyazhuang * */ public class SendTest { /** * * QQ邮箱 POP3 和 SMTP 服务器地址设置如下:邮箱POP3服务器(端口110)SMTP服务器(端口25)qq.com pop.qq.com smtp.qq.comSMTP服务器需要身份验证。 如果是设置POP3和SMTP的SSL加密方式,则端口如下: POP3服务器(端口995) SMTP服务器(端口465或587)。 * @param args */ public static void main(String[] args) throws Exception{ Properties prop = new Properties(); InputStream in = SendTest.class.getResourceAsStream("/email.properties"); prop.load(in); MailSenderInfo mailInfo = new MailSenderInfo(); mailInfo.setMailServerHost(prop.getProperty("mail_server_host")); mailInfo.setMailServerPort(prop.getProperty("mail_server_port")); mailInfo.setUserName(prop.getProperty("mail_user_name")); mailInfo.setPassword(prop.getProperty("mail_password")); mailInfo.setFromAddress(prop.getProperty("mail_from_address")); mailInfo.setValidate(true); mailInfo.setToAddress("你要发送邮件的目标邮箱"); mailInfo.setSubject("你好"); mailInfo.setContent("我叫刘亚壮"); // 这个类主要来发送邮件 MailSender.sendTextMailWithAttachment(mailInfo);// 发送文体格式 } }
大家可以到链接http://download.csdn.net/detail/l1028386804/9490320下载开发邮件程序所需要的jar包,到链接http://download.csdn.net/detail/l1028386804/9490326下载java发送邮件的完整源代码