Spring中javaMail通过SMTP发送邮件

1、如果是maven项目,需要引入依赖包

<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.4</version>
</dependency>

2、在项目加载的basic.xml中,配置两个bean:JavaMailSenderImpl和SimpleMailMessage,在后续发送邮件中通过这两个类进行发送

<bean id="javaMailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" >
<value>----</value>
</property>
<property name="port" >
<value type="java.lang.Integer">----</value>
</property>
<property name="protocol">
<value>smtps</value>
</property>
<property name="username">
<value>----</value>
</property>
<property name="password">
<value>----</value>
</property>
<!-- SMTP服务器验证 -->
<property name="javaMailProperties">
<props>
<!-- 验证身份 -->
<prop key="mail.smtps.auth">true</prop>
<prop key="mail.smtp.ssl.enable">true</prop>
<prop key="mail.transport.protocol">smtps</prop>
</props>
</property>
</bean>

<bean id="simpleMailMessage" class="org.springframework.mail.SimpleMailMessage">
<property name="from">
<value>${notify_service.smtp_mail.username}</value>
</property>
</bean>

 

private MailSender mailSender;
private SimpleMailMessage simpleMailMessage;

//初始化mailSender 和SimpleMailMessage 两个对象

simpleMailMessage.setTo(sendTo);
simpleMailMessage.setSubject(subject);
simpleMailMessage.setText(content);
mailSender.send(simpleMailMessage);

另外如果是发送HTML格式的邮件

import javax.mail.MessagingException;  

import javax.mail.internet.MimeMessage;  

import org.springframework.mail.SimpleMailMessage;  

import org.springframework.mail.javamail.JavaMailSender;  

import org.springframework.mail.javamail.MimeMessageHelper;  

private JavaMailSender javaMailSender;  

private MimeMessage mimeMessage;  

private MimeMessageHelper mimeMessageHelper;  

private SimpleMailMessage simpleMailMessage;  

try {  

mimeMessage = javaMailSender.createMimeMessage();
mimeMessageHelper = new MimeMessageHelper(mimeMessage,true,"GBK");
mimeMessageHelper.setFrom(simpleMailMessage.getFrom());
mimeMessageHelper.setTo(sendTo);
mimeMessageHelper.setSubject(subject);
mimeMessageHelper.setText(content);
javaMailSender.send(mimeMessage);
} catch (MessagingException e) {
e.printStackTrace();
}

===========================================================================

 

posted on 2017-07-12 18:53  离夏  阅读(214)  评论(0编辑  收藏  举报