Spring2.5中的JavaMailSenderImpl、MimeMessageHelper
程序员文章站
2022-04-19 21:38:22
...
<!-- Email支持 -->
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host">
<value>smtp.exmail.qq.com</value>
</property>
<property name="username">
<value>[email protected]</value>
</property>
<property name="port">
<value>25</value>
</property>
<property name="password">
<value>2013loongtao2013</value>
</property>
<property name="javaMailProperties">
<props>
<prop key="mail.smtp.auth">true</prop>
<prop key="mail.smtp.timeout">25000</prop>
</props>
</property>
</bean>
Java代码
public void testSendEmail(){
try {
JavaMailSenderImpl mailSender=new JavaMailSenderImpl();
mailSender.setHost("服务器名");
mailSender.setPort(3306);
mailSender.setUsername("用户名");
mailSender.setPassword("密码");
MimeMessage msg = mailSender.createMimeMessage();
// 设置utf-8或GBK编码,否则邮件会有乱码,true表示为multipart邮件
MimeMessageHelper helper = new MimeMessageHelper(msg, true, "utf-8");
// 邮件接收地址
helper.setTo("[email protected]");
// 设置抄送
helper.setBcc(new InternetAddress("[email protected]","接收人","utf-8"));
// 设置发送人邮件地址
helper.setFrom("[email protected]","发送人");
//设置发送邮件的标题
helper.setSubject("发送邮件的标题");
// 设置邮件内容,注意加参数true,表示启用html格式
helper.setText("发送邮件的内容...", true);
//发送带有附件的可以省略...参数一:读取word文档,参数二:
helper.addAttachment(MimeUtility.encodeWord("Word文件名"), new FileSystemResource(new File("文件地址")));//第一个参数附件名,第二个参数附件
//发送邮件
mailSender.send(msg);
System.out.println("发送成功");
} catch (MailException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
}
转载于:https://my.oschina.net/u/1163293/blog/170851