pom.xml
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.1</version>
</dependency>
applicationcontext-email
<?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:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<!-- 163邮箱,smtp.163.com -->
<!-- admin@163.com 用户名:admin 授权码:xxx -->
<!-- smtp邮件发送协议 -->
<!-- pop3收邮件协议 -->
<property name="host" value="smtp.163.com" />
<property name="username" value="123456" />
<property name="password" value="xxxxxxx" />
<property name="javaMailProperties">
<props>
<!-- 必须进行授权认证,它的目的就是阻止他人任意乱发邮件 -->
<prop key="mail.smtp.auth">true</prop>
<!-- SMTP加密方式:连接到一个TLS保护连接 -->
<prop key="mail.smtp.starttls.enable">true</prop>
</props>
</property>
</bean>
</beans>
public class MailTest extends BaseServiceTest {
@Test
public void testName() throws Exception {
// 简单邮件对象
SimpleMailMessage msg = new SimpleMailMessage();
// 发送人:和配置一致
msg.setFrom("123@126.com");
// 收件人
msg.setTo("123@163.com");
// 主题
msg.setSubject("adc");
// 内容
msg.setText("asd");
// 设置固定回邮地址
//msg.setReplyTo("xxxx@xxx.com");
// 发送
mailSender.send(msg);
}
/**
* 发送复杂邮件
*/
@Test
public void testSendMsg2() throws MessagingException {
//创建复杂的邮件发送
MimeMessage mimeMessage = mailSender.createMimeMessage();
//复杂邮件的工具类
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true,"UTF-8");
helper.setFrom("123@126.com");
helper.setTo("123@163.com");
helper.setSubject("测试一把");
helper.setText("<h1>123</h1>",true);
//发送附件
helper.addAttachment("123.jpg",new File("E:/timg.jpg"));
helper.addAttachment("java.docx",new File("E:/新建文本文档 (2).txt"));
mailSender.send(mimeMessage);
}
}