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();
}

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

 

转载于:https://www.cnblogs.com/awayInSummer/p/7157106.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值