一、简介
JavaMail API提供了一种与平台无关和协议独立的框架来构建邮件和消息应用程序。 JavaMail API提供了一组抽象类定义构成一个邮件系统的对象。它是阅读,撰写和发送电子信息的可选包(标准扩展)。
JavaMail 规定,用于构造一个接口,一个消息传送系统中的元素,包括系统的部件和接口。虽然本规范没有定义任何特定的实现,JavaMail是否包括实现RFC822和MIME Internet邮件标准几类。这些类都作为JavaMail的类包的一部分。
二、参考资料
中文教程
牛人的学习
三、准备jar
mail.jar 下载地址
activation.jar 下载地址
导入项目
四、功能
1、发送邮件
2、发送带有附件的电子邮件
3、发送一个html电子邮件
4、发送图片的电子邮件
5、查询电子邮件
五、实例
【注:本实例使用的qq邮箱】
准备以下的工作:
1、获取邮箱服务器地址:
2、获取端口号:
3、设置独立密码:
4、开启服务器功能:
5、授权码:
6、如果是使用qq邮箱,必须加上这两个:
prop.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); prop.setProperty("mail.smtp.socketFactory.port", "465");
【注意:现在很多邮箱都需要设置smtp、pop3的设置,需要手动的开启。】
2、实现
发送邮件需要的属性Model
package com.wuhn.model; /** * @author wuhn * @创建时间 2015-12-18 * @功能 javamail 发送简单的电子邮件 * **/ public class SendEmailModel { private String to;//收件人邮箱 private String from;//发送人邮箱 private String username;//发送人账号 private String password;//发送人密码 qq授权码 private String host;//smtp服务器(邮件发送服务器)这里使用的是qq服务器 private String port;//端口 public String getTo() { return to; } public void setTo(String to) { this.to = to; } public String getFrom() { return from; } public void setFrom(String from) { this.from = from; } 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 String getHost() { return host; } public void setHost(String host) { this.host = host; } public String getPort() { return port; } public void setPort(String port) { this.port = port; } }
获取邮箱服务器
package com.wuhn.utils; import java.util.Properties; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.Store; import com.wuhn.model.SendEmailModel; /** * @author wuhn * @创建时间 2015-12-18 * @功能 javamail 邮件检查和提取 * **/ public class CheckingMails { /** * @功能 设置连接pop3邮件的属性 邮件接收服务器 * @param SendEmailModel sendMailModel * @return Properties properties * **/ public static Properties setPop3Properties(SendEmailModel sendMailModel){ Properties properties = new Properties(); properties.put("mail.pop3.host", sendMailModel.getHost()); properties.put("mail.pop3.port", sendMailModel.getPort()); properties.put("mail.pop3.starttls.enable", "true"); return properties; } /** * @功能 设置创建pop3 store并连接pop服务器 * @param SendEmailModel sendMailModel * Properties properties * @return Store store * @throws MessagingException * **/ public static Store getStore(SendEmailModel sendMailModel,Properties properties) throws MessagingException{ //获取session Session emailSession = Session.getDefaultInstance(properties); emailSession.setDebug(true); //创建pop3 store Store store = emailSession.getStore("pop3s"); //连接pop服务器 store.connect(sendMailModel.getHost(),sendMailModel.getUsername(),sendMailModel.getPassword()); return store; } }
package com.wuhn.utils; import java.util.Properties; import javax.activation.DataHandler; import javax.activation.DataSource; import javax.activation.FileDataSource; import javax.mail.BodyPart; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Multipart; import javax.mail.PasswordAuthentication; import javax.mail.Session; 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.wuhn.model.EmailModel; import com.wuhn.model.SendEmailModel; /** * @author wuhn * @创建时间 2015-12-17 * @功能 javamail 公用方法 * **/ public class SendEmailUtil { /** * @功能 设置连接smtp邮件的属性 * @param SendEmailModel sendMailModel * @return Properties props * **/ public static Properties setSmtpProperties(SendEmailModel sendMailModel){ Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", sendMailModel.getHost()); props.put("mail.smtp.port", sendMailModel.getPort()); //需要加上 props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.put("mail.smtp.socketFactory.port", sendMailModel.getPort()); return props; } /** * @功能 获取session * @param SendEmailModel sendMailModel * Properties props * @return Session session * **/ public static Session getSession(final SendEmailModel sendMailModel,Properties props){ Session session = Session.getInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(sendMailModel.getUsername(), sendMailModel.getPassword()); } }); session.setDebug(true);//开启session调试 return session; } /** * @功能 创建一个MimeMessage对象(Message类是创建和解析邮件内容的API,它的实例对象代表一封电子邮件。) * @param SendEmailModel sendMailModel * MailModel mailModel * Session session * @return Message message * @throws MessagingException * @throws AddressException * **/ public static Message setMimeMessage(SendEmailModel sendMailModel,EmailModel mailModel,Session session) throws AddressException, MessagingException{ //创建一个MimeMessage对象(Message类是创建和解析邮件内容的API,它的实例对象代表一封电子邮件。) Message message = new MimeMessage(session); //指明邮件的发件人 message.setFrom(new InternetAddress(sendMailModel.getFrom())); //指明邮件的收件人 message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(sendMailModel.getTo())); //邮件的标题 message.setSubject(mailModel.getSubject()); //邮件的文本内容 message.setText(mailModel.getText()); //邮件的html内容 优先显示 if(mailModel.getHtml()!=null){ message.setContent(mailModel.getHtml(), "text/html"); } return message; } /** * @功能 创建message对象 带附件的邮件 * @param SendEmailModel sendMailModel * MailModel mailModel * Session session * @return Message message * @throws MessagingException * @throws AddressException * **/ public static Message setMessageBodyPart(SendEmailModel sendMailModel,EmailModel mailModel,Session session) throws AddressException, MessagingException{ //创建一个MimeMessage对象(Message类是创建和解析邮件内容的API,它的实例对象代表一封电子邮件。) Message message = new MimeMessage(session); //指明邮件的发件人 message.setFrom(new InternetAddress(sendMailModel.getFrom())); //指明邮件的收件人 message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(sendMailModel.getTo())); //邮件的标题 message.setSubject(mailModel.getSubject()); //message.setText(mailModel.getText()); //创建一个Multipart message【可以包含多个MimeBodyPart】 Multipart multipart = new MimeMultipart(); //创建第一个MimeBodyPart,设置邮件内容【MimeBodyPart也可以再包含一个Multipart】 BodyPart messageBodyPart = new MimeBodyPart(); //邮件的文本内容 messageBodyPart.setText("This is message body"); multipart.addBodyPart(messageBodyPart); //创建第二个MimeBodyPart,设置邮件附件 messageBodyPart = new MimeBodyPart(); String filename = mailModel.getFile(); DataSource source = new FileDataSource(filename); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(filename); multipart.addBodyPart(messageBodyPart); //完成message的组装 message.setContent(multipart); return message; } /** * @功能 创建message对象 带图片的邮件 * @param SendEmailModel sendMailModel * MailModel mailModel * Session session * @return Message message * @throws MessagingException * @throws AddressException * **/ public static Message setInlineImages(SendEmailModel sendMailModel,EmailModel mailModel,Session session) throws AddressException, MessagingException{ //创建一个MimeMessage对象(Message类是创建和解析邮件内容的API,它的实例对象代表一封电子邮件。) Message message = new MimeMessage(session); //指明邮件的发件人 message.setFrom(new InternetAddress(sendMailModel.getFrom())); //指明邮件的收件人 message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(sendMailModel.getTo())); //邮件的标题 message.setSubject(mailModel.getSubject()); //message.setText(mailModel.getText()); //创建一个Multipart message【可以包含多个MimeBodyPart】 Multipart multipart = new MimeMultipart("related"); //创建第一个MimeBodyPart,设置邮件内容【MimeBodyPart也可以再包含一个Multipart】 BodyPart messageBodyPart = new MimeBodyPart(); //邮件的文本内容 messageBodyPart.setContent(mailModel.getHtml(), "text/html"); multipart.addBodyPart(messageBodyPart); //创建第二个MimeBodyPart,设置邮件附件 messageBodyPart = new MimeBodyPart(); String filename = mailModel.getFile(); DataSource source = new FileDataSource(filename); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setHeader("Content-ID", "<image>"); multipart.addBodyPart(messageBodyPart); //完成message的组装 message.setContent(multipart); return message; } }
发送邮件
package com.wuhn.mail; import java.util.Properties; import javax.mail.Message; import javax.mail.Session; import javax.mail.Transport; import com.wuhn.model.EmailModel; import com.wuhn.model.SendEmailModel; import com.wuhn.utils.SendEmailUtil; /** * @author wuhn * @创建时间 2015-12-17 * @功能 javamail * **/ public class SendEmail { /** * @功能 发送简单的电子邮件 * @param SendEmailModel sendMailModel * MailModel mailModel * @return void * **/ public static void sendEmail(SendEmailModel sendMailModel,EmailModel mailModel) { //设置Properties Properties props = SendEmailUtil.setSmtpProperties(sendMailModel); //获取一个session Session session = SendEmailUtil.getSession(sendMailModel, props); try { //创建一个默认MimeMessage对象,并设置发件人、收件人、主题(From、To、Subject)在消息中。 Message message = SendEmailUtil.setMimeMessage(sendMailModel, mailModel, session); //发送邮件 Transport.send(message); System.out.println("发送邮件...成功!"); } catch (Exception e) { System.out.println("发送邮件...失败!"); e.printStackTrace(); } } /** * @功能 发送带有附件的电子邮件 * @param SendEmailModel sendMailModel * MailModel mailModel * @return void * **/ public static void sendAttachmentInEmail(SendEmailModel sendMailModel,EmailModel mailModel) { //设置Properties Properties props = SendEmailUtil.setSmtpProperties(sendMailModel); //获取一个session Session session = SendEmailUtil.getSession(sendMailModel, props); try { //创建一个默认MimeMessage对象,并设置发件人、收件人、主题(From、To、Subject)在消息中。 Message message = SendEmailUtil.setMessageBodyPart(sendMailModel, mailModel, session); //发送邮件 Transport.send(message); System.out.println("发送邮件...成功!"); } catch (Exception e) { System.out.println("发送邮件...失败!"); e.printStackTrace(); } } /** * @功能 发送带有图片的电子邮件 * @param SendEmailModel sendMailModel * MailModel mailModel * @return void * **/ public static void sendInlineImagesInEmail(SendEmailModel sendMailModel,EmailModel mailModel) { //设置Properties Properties props = SendEmailUtil.setSmtpProperties(sendMailModel); //获取一个session Session session = SendEmailUtil.getSession(sendMailModel, props); try { //创建一个默认MimeMessage对象,并设置发件人、收件人、主题(From、To、Subject)在消息中。 Message message = SendEmailUtil.setInlineImages(sendMailModel, mailModel, session); //发送邮件 Transport.send(message); System.out.println("发送邮件...成功!"); } catch (Exception e) { System.out.println("发送邮件...失败!"); e.printStackTrace(); } } }
package com.wuhn.mail; import java.io.IOException; import java.util.Properties; import javax.mail.Folder; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Store; import com.wuhn.model.EmailModel; import com.wuhn.model.SendEmailModel; import com.wuhn.utils.CheckingMails; /** * @author wuhn * @创建时间 2015-12-18 * @功能 javamail 邮件检查和提取 * **/ public class ReceiveEmail { /** * @功能 邮件检查和提取 * @param SendEmailModel sendMailModel * @return void * @throws MessagingException * @throws IOException * **/ public static void receiveEmail(SendEmailModel sendMailModel) throws MessagingException, IOException { Properties properties = CheckingMails.setPop3Properties(sendMailModel); Store store = CheckingMails.getStore(sendMailModel, properties); //创建一个文件夹并打开它 Folder emailFolder = store.getFolder("INBOX"); emailFolder.open(Folder.READ_ONLY); //从folder中获取这些邮件信息并打印出来 Message[] messages = emailFolder.getMessages(); System.out.println("邮件总数:" + messages.length); for (int i = 0, n = messages.length; i < n; i++) { Message message = messages[i]; System.out.println("---------------------------------"); System.out.println("Email Number " + (i + 1)); System.out.println("Subject: " + message.getSubject()); System.out.println("From: " + message.getFrom()[0]); System.out.println("Text: " + message.getContent().toString()); } //关闭store和Folder emailFolder.close(false); store.close(); } }
package com.wuhn.mail; import java.io.IOException; import javax.mail.MessagingException; import org.junit.After; import org.junit.Before; import org.junit.Test; import com.wuhn.model.EmailModel; import com.wuhn.model.SendEmailModel; /** * @author wuhn * @创建时间 2015-12-17 * @功能 javamail 正式测试 * **/ public class FormalTest { @Before public void testBefore(){ System.out.println("*******开始测试*******"); } @After public void testAfter(){ System.out.println("*******结束测试*******"); } @Test public void testSendMail(){ System.out.println("*******简单邮件发送*******"); //设置初始化属性 SendEmailModel sendMailModel = new SendEmailModel(); sendMailModel.setTo("[email protected]"); sendMailModel.setFrom("[email protected]"); sendMailModel.setUsername("[email protected]"); sendMailModel.setPassword(""); sendMailModel.setPort("465"); sendMailModel.setHost("smtp.qq.com"); EmailModel mailModel = new EmailModel(); mailModel.setSubject("测试发送邮件"); mailModel.setText("这是一个测试内容!"); SendEmail.sendEmail(sendMailModel, mailModel); } @Test public void testSendAttachmentInEmail(){ System.out.println("*******带附件邮件发送*******"); //设置初始化属性 SendEmailModel sendMailModel = new SendEmailModel(); sendMailModel.setTo("[email protected]"); sendMailModel.setFrom("[email protected]"); sendMailModel.setUsername("[email protected]"); sendMailModel.setPassword(""); sendMailModel.setPort("465"); sendMailModel.setHost("smtp.qq.com"); EmailModel mailModel = new EmailModel(); mailModel.setSubject("测试发送邮件"); mailModel.setText("这是一个测试内容!"); mailModel.setFile("src\\111111.txt"); SendEmail.sendAttachmentInEmail(sendMailModel, mailModel); } @Test public void testSendHTMLEmail(){ System.out.println("*******带html邮件发送*******"); //设置初始化属性 SendEmailModel sendMailModel = new SendEmailModel(); sendMailModel.setTo("[email protected]"); sendMailModel.setFrom("[email protected]"); sendMailModel.setUsername("[email protected]"); sendMailModel.setPassword(""); sendMailModel.setPort("465"); sendMailModel.setHost("smtp.qq.com"); EmailModel mailModel = new EmailModel(); mailModel.setSubject("测试发送邮件"); mailModel.setText("这是一个测试内容!"); mailModel.setHtml("<h1>This is actual message embedded in HTML tags</h1>"); SendEmail.sendEmail(sendMailModel, mailModel); } @Test public void testSendInlineImagesInEmail(){ System.out.println("*******带图片邮件发送*******"); //设置初始化属性 SendEmailModel sendMailModel = new SendEmailModel(); sendMailModel.setTo("[email protected]"); sendMailModel.setFrom("[email protected]"); sendMailModel.setUsername("[email protected]"); sendMailModel.setPassword(""); sendMailModel.setPort("465"); sendMailModel.setHost("smtp.qq.com"); EmailModel mailModel = new EmailModel(); mailModel.setSubject("测试发送邮件"); mailModel.setFile("src\\01.jpg"); mailModel.setHtml("<H1>Hello</H1><img src='cid:image'>"); SendEmail.sendInlineImagesInEmail(sendMailModel, mailModel); } @Test public void testReceiveEmail(){ System.out.println("*******带图片邮件发送*******"); //设置初始化属性 SendEmailModel sendMailModel = new SendEmailModel(); sendMailModel.setTo("[email protected]"); sendMailModel.setFrom("[email protected]"); sendMailModel.setUsername("[email protected]"); sendMailModel.setPassword(""); sendMailModel.setPort("995"); sendMailModel.setHost("pop.qq.com"); try { ReceiveEmail.receiveEmail(sendMailModel); } catch (MessagingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
4、代码下载
点击这里