一, 用于处理电子邮件相关的编程接口,javaMail 是由Sun定义的一套收发电子邮件的API,它可以方便地执行一些常用的邮件传输,不同的厂商可以提供自己的实现类,但它并没有包含在jdk中,而是作为javaEE的一部分。
二, 厂商所提供的javamail服务程序可以有选择的实现某些邮件协议,常见的邮件协议: -SMTP: 简单邮件传输协议,用于发送电子邮件的传输协议 -POP3: 用于接收电子邮件的标准协议。 -IMAP: 互联网消息协议,是POP3的替代协议。 -三种协议都有对应SSL加密传输的协议,分别是 SMTPS, POP3S,和IMAPS 。除JavaMail 服务提供程序之外,JavaMail还需要JAF (JavaBeans Activation Framework) 来处理不是纯文本的邮件内容,包括MIME(多用途互联网邮件扩展),URL 页面和文件附件等内容。另外,JavaMail 依赖 JAF (JavaBeans Activation Framework),JAF 在Java6之后已经合并到JDK中,而JDK5之前需要另外下载JAF的类库。
三,JavaMail 关键对象 四,添加JavaMail相关依赖 在Maven项目中的pom.xml配置文件中添加mail所需的依赖
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.6.2</version>
</dependency>
<dependency>
<groupId>javax.mail</groupId>
<artifactId>javax.mail-api</artifactId>
<version>1.6.2</version>
</dependency>
五,发送普通文本邮件
public class MailTest {
public static void main(String [] args ) throws Exception{
Properties prop = new Properties ();
prop.setProperty("mail.smtp.host","smtp.163.com");
prop.setProperty("mail.smtp.port","25");
prop.setProperty("mail.smtp.auth","true");
prop.setProperty("mail.smtp.port","465");
prop.setProperty("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
prop.setProperty("mail.smtp.socketFactory.fallback","false");
prop.setProperty("mail.smtp.socketFactory.port","465");
Session session = Session.getInstance(prop);
session.setDebug(true);
Transport transport = session.getTransport();
transport.connect("smtp.163.com","lwj18475","PQQVRNRONLXASWQZ");
Message message= createSimpleMail(session);
transport.sendMessage(message , message.getAllRecipients());
transport.close();
}
public static Message createSimpleMail(Session session) throws MessagingException {
MimeMessage message = new MimeMessage(session);
message.setFrom("lwj18475@163.com");
message.setRecipients(Message.RecipientType.TO,"lwj18475@163.com");
message.setSubject("测试文本邮件!");
message.setSentDate(new Date());
message.setText("Hello,Vodka!");
return message;
}
}
六,发送带附件的邮件
package com.vodka.Test;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.util.Date;
import java.util.Properties;
public class MailTest {
public static void main(String [] args ) throws Exception{
Properties prop = new Properties ();
prop.setProperty("mail.smtp.host","smtp.163.com");
prop.setProperty("mail.smtp.port","25");
prop.setProperty("mail.smtp.auth","true");
prop.setProperty("mail.smtp.port","465");
prop.setProperty("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
prop.setProperty("mail.smtp.socketFactory.fallback","false");
prop.setProperty("mail.smtp.socketFactory.port","465");
Session session = Session.getInstance(prop);
session.setDebug(true);
Transport transport = session.getTransport();
transport.connect("smtp.163.com","lwj18475","PQQVRNRONLXASWQZ");
Message message= createAttachMail(session);
transport.sendMessage(message , message.getAllRecipients());
transport.close();
}
public static Message createAttachMail(Session session) throws MessagingException {
MimeMessage message = new MimeMessage(session);
message.setFrom("lwj18475@163.com");
message.setRecipients(Message.RecipientType.TO,"lwj18475@163.com");
message.setSubject("含带附件的邮件!");
message.setSentDate(new Date());
MimeBodyPart bodyPart = new MimeBodyPart();
bodyPart.setContent("一封带附件的邮件","text/html; charset=utf-8");
MimeMultipart mimeMultipart = new MimeMultipart();
MimeBodyPart attachPart = new MimeBodyPart();
DataHandler dataHandler = new DataHandler(new FileDataSource("C:\\Users\\伟神\\Desktop\\Hotel\\VipRoom.jpg"));
attachPart.setDataHandler(dataHandler);
attachPart.setFileName("Spring.Log");
mimeMultipart.addBodyPart(bodyPart);
mimeMultipart.addBodyPart(attachPart);
mimeMultipart.setSubType("mixed");
message.setContent(mimeMultipart);
return message;
}
}
七,Html内容的邮件
八,
1。邮件信息配置封装类
public class MailConfiguration {
private String Host;
private String Port;
private String FromAddress;
private List<String> AllRecipients;
private String UserName;
private String UserPwd;
private boolean Authentic = true;
private String Subject;
private String Content;
private List<String> AttachFiles;
public MailConfiguration() {
}
public MailConfiguration(String host, String port, String fromAddress, List<String> allRecipients, String userName, String userPwd, boolean authentic, String subject, String content, List<String> attachFiles) {
Host = host;
Port = port;
FromAddress = fromAddress;
AllRecipients = allRecipients;
UserName = userName;
UserPwd = userPwd;
Authentic = authentic;
Subject = subject;
Content = content;
AttachFiles = attachFiles;
}
public String getHost() {
return Host;
}
public void setHost(String host) {
Host = host;
}
public String getPort() {
return Port;
}
public void setPort(String port) {
Port = port;
}
public String getFromAddress() {
return FromAddress;
}
public void setFromAddress(String fromAddress) {
FromAddress = fromAddress;
}
public List<String> getAllRecipients() {
return AllRecipients;
}
public void setAllRecipients(List<String> allRecipients) {
AllRecipients = allRecipients;
}
public String getUserName() {
return UserName;
}
public void setUserName(String userName) {
UserName = userName;
}
public String getUserPwd() {
return UserPwd;
}
public void setUserPwd(String userPwd) {
UserPwd = userPwd;
}
public boolean isAuthentic() {
return Authentic;
}
public void setAuthentic(boolean authentic) {
Authentic = authentic;
}
public String getSubject() {
return Subject;
}
public void setSubject(String subject) {
Subject = subject;
}
public String getContent() {
return Content;
}
public void setContent(String content) {
Content = content;
}
public List<String> getAttachFiles() {
return AttachFiles;
}
public void setAttachFiles(List<String> attachFiles) {
AttachFiles = attachFiles;
}
@Override
public String toString() {
return "MailConfiguration{" +
"Host='" + Host + '\'' +
", Port='" + Port + '\'' +
", FromAddress='" + FromAddress + '\'' +
", AllRecipients=" + AllRecipients +
", UserName='" + UserName + '\'' +
", UserPwd='" + UserPwd + '\'' +
", Authentic=" + Authentic +
", Subject='" + Subject + '\'' +
", Content='" + Content + '\'' +
", AttachFiles=" + AttachFiles +
'}';
}
}
2.身份认证类
public class MyAuthenticator extends Authenticator {
private String UserName;
private String UserPwd;
public MyAuthenticator(String userName , String userPwd){
this.UserName = userName;
this.UserPwd = userPwd;
}
protected PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication(UserName,UserPwd);
}
}
3.邮件发送类
public class MailSender {
public void sendMail(MailConfiguration mc) throws Exception {
Properties prop = new Properties ();
prop.setProperty("mail.smtp.host",mc.getHost());
prop.setProperty("mail.smtp.port",mc.getPort());
prop.setProperty("mail.smtp.auth", String.valueOf(mc.isAuthentic()));
MyAuthenticator myAuthenticator = new MyAuthenticator(mc.getUserName(),mc.getUserPwd());
Session session = Session.getDefaultInstance(prop,myAuthenticator);
session.setDebug(true);
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(mc.getFromAddress()));
message.setSubject(mc.getSubject());
message.setSentDate(new Date());
if(mc.getAllRecipients() != null && mc.getAllRecipients().size() > 0){
Address[] addresses = new Address[mc.getAllRecipients().size()];
for(int index = 0 ; index < mc.getAllRecipients().size() ; ++index){
Address address = new InternetAddress(mc.getAllRecipients().get(index));
addresses[index] = address;
}
message.setRecipients(Message.RecipientType.TO,addresses);
}
MimeMultipart mimeMultipart = new MimeMultipart();
MimeBodyPart mimeBodyPart = new MimeBodyPart();
mimeBodyPart.setContent(mc.getContent(),"text/html;character=UTF-8");
mimeMultipart.addBodyPart(mimeBodyPart);
List<String> AttachFiles = mc.getAttachFiles();
MimeBodyPart attachFile = null;
if(AttachFiles != null && AttachFiles.size() > 0 ){
File tempFile = null;
for (int index = 0 ; index < AttachFiles.size(); index++){
attachFile = new MimeBodyPart();
tempFile = new File(AttachFiles.get(index));
if(tempFile != null){
DataHandler dataHandler = new DataHandler(new FileDataSource(tempFile));
attachFile.setDataHandler(dataHandler);
attachFile.setFileName(MimeUtility.decodeText(tempFile.getName()));
mimeMultipart.addBodyPart(attachFile);
}
}
}
message.setContent(mimeMultipart);
Transport.send(message);
}
}
4.测试类
@Test
public void MailTest() throws Exception {
MailConfiguration mailConfiguration = new MailConfiguration();
mailConfiguration.setHost("smtp.163.com");
mailConfiguration.setPort("25");
mailConfiguration.setUserName("lwj18475");
mailConfiguration.setUserPwd("xxxxxxxxxx");
mailConfiguration.setSubject("邮件封装测试");
mailConfiguration.setFromAddress("lwj18475@163.com");
List<String> Recipients = new ArrayList<>();
Recipients.add("lwj18475@163.com");
mailConfiguration.setAllRecipients(Recipients);
mailConfiguration.setContent("<h1>Hello Vodka!");
MailSender mailSender = new MailSender();
List<String> files = new ArrayList<>();
files.add("C:\\Users\\伟神\\Desktop\\Hotel\\VipRoom.jpg");
files.add("D:\\VipRoom.jpg");
mailConfiguration.setAttachFiles(files);
mailSender.sendMail(mailConfiguration);
}
九,使用Spring 的Mail API 1.配置pom.xml
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version> 5.3.9</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>5.2.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.3.2.RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.6.2</version>
</dependency>
2.定义spring配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com.vodka" />
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value="smtp.163.com"></property>
<property name="port" value="25"></property>
<property name="defaultEncoding" value="UTF-8"></property>
<property name="username" value="lwj18475"></property>
<property name="password" value="xxxxxxxxxxxxxxxxxx"></property>
</bean>
<bean id="templateMessage" class="org.springframework.mail.SimpleMailMessage">
<property name="from" value="lwj18475@163.com"></property>
<property name="subject" value="SpringMailApiTest"></property>
</bean>
</beans>
3.定义接口和实现类
public interface OrderManager {
void placeOrder();
}
@Service
public class ManagerOrderImp implements OrderManager{
@Autowired
private MailSender mailSender;
@Autowired
private SimpleMailMessage simpleMailMessage;
@Override
public void placeOrder(){
SimpleMailMessage msg = new SimpleMailMessage(this.simpleMailMessage);
msg.setTo("lwj18475@163.com");
msg.setText("veryGood");
try{
this.mailSender.send(msg);
}catch(MailException ex){
System.err.println(ex.getMessage());
}
}
}
public class TestMailFunction {
public static void main(String[] args){
BeanFactory beanFactory = new ClassPathXmlApplicationContext("spring.xml");
ManagerOrderImp managerOrderImp = (ManagerOrderImp) beanFactory.getBean("managerOrderImp");
managerOrderImp.placeOrder();
}
}
public class TestMailFunction {
public static void main(String[] args) throws MessagingException {
BeanFactory beanFactory = new ClassPathXmlApplicationContext("spring.xml");
JavaMailSender javaMailSendermailSender = (JavaMailSender) beanFactory.getBean("mailSender");
MimeMessage mimeMessage = javaMailSendermailSender.createMimeMessage();
mimeMessage.setSubject("SpringMailTest-AttachFiles");
MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage,true,"utf-8");
mimeMessageHelper.setTo("lwj18475@163.com");
mimeMessageHelper.setText("<h1>敬赠</h1>");
mimeMessageHelper.setFrom("lwj18475@163.com");
File file = new File("D:\\敬赠.txt");
mimeMessageHelper.addAttachment(file.getName(),file);
javaMailSendermailSender.send(mimeMessage);
}
}
|