Spring邮件抽象层的主要包为org.springframework.mail。它包括了发送电子邮件的主要接口MailSender,和值对象SimpleMailMessage,它封装了简单邮件的属性如from, to,cc, subject,text。 包里还包含一棵以MailException为根的checked Exception继承树,它们提供了对底层邮件系统异常的高级别抽象。 要获得关于邮件异常层次的更丰富的信息,请参考Javadocs。
为了使用JavaMail中的一些特色, 比如MIME类型的信件, Spring提供了MailSender的一个子接口, 即org.springframework.mail.javamail.JavaMailSender。Spring还提供了一个回调接口org.springframework.mail.javamail.MimeMessagePreparator, 用于准备JavaMail的MIME信件。
package cn.tes.mail;
import java.io.File;
import java.util.Properties;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
public class SpringMail {
public static void htmlMail() throws MessagingException{
JavaMailSenderImpl mailSV = new JavaMailSenderImpl();
mailSV.setHost("smtp.qq.com");
MimeMessage mailMsg = mailSV.createMimeMessage();
MimeMessageHelper mailMsgHelper = new MimeMessageHelper(mailMsg,true);
mailMsgHelper.setFrom("*****@qq.com"); //发件人
mailMsgHelper.setTo("*****@163.com");//收件人
mailMsgHelper.setSubject("测试邮件");
//true 表示启动HTML格式的邮件
mailMsgHelper.setText("<html><head></head><body><h1>hello!!spring html Mail</h1>" +
"<img src=\"cid:aaa\"/></body></html>",true);
// 添加图片
FileSystemResource img = new FileSystemResource(new File("f://aaa.jpg"));
mailMsgHelper.addInline("aaa",img);
//添加附件
FileSystemResource file = new FileSystemResource(new File("f://aaa.jpg"));
mailMsgHelper.addAttachment("aaa.jpg",file);
mailSV.setUsername("*****@qq.com");
mailSV.setPassword("*****");
Properties prop = new Properties();
prop.put("mail.smtp.auth", "true") ; // 将这个参数设为true,让服务器进行认证,认证用户名和密码是否正确
prop.put("mail.smtp.timeout", "25000") ;
mailSV.setJavaMailProperties(prop);
mailSV.send(mailMsg);
System.out.println("邮件发送成功");
}
public static void main(String[] args) throws MessagingException {
htmlMail();
}
}
转载于:https://blog.51cto.com/lxy2020/1568510