标签:
一.首先开启SMTP服务
在 QQ 邮箱里的 设置->账户->开启 SMTP 服务
注意:开启完之后,QQ 邮箱会生成一个授权码,在代码里连接邮箱使用这个授权码而不是原始的邮箱密码,这样可以避免使用明文密码
二.设置spring配置文件
<?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"
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">
<!-- Spring封装JavaMail的发送对象 -->
<bean id="sender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<!-- SMTP服务器,必填 -->
<property name="host" value="smtp.qq.com" />
<!-- 端口,可选 -->
<property name="port" value="587" />
<!-- 发送者邮箱用户名,必填 -->
<property name="username" value="973172866@qq.com" />
<!-- 发送者邮箱密码,必填 动态密码-->
<property name="password" value="rtebhgirhuqwbfgi" />
<!-- 发送协议,可选 -->
<property name="protocol" value="smtp" />
<!-- 默认字符集,可选 -->
<property name="defaultEncoding" value="utf-8" />
<!-- JavaMail配置信息,必填 -->
<property name="javaMailProperties">
<props>
<prop key="mail.smtp.auth">true</prop>
</props>
</property>
</bean>
<bean id="simpleMailSender" class="com.spring.mail.demo1.SimpleMailSender">
<property name="javaMailSender" ref="sender" />
</bean>
<bean id="attachmentSender" class="com.springmail.demo2.AttachmentSender">
<property name="javaMailSender" ref="sender" />
</bean>
<bean id="htmlSender" class="com.springmail.demo3.HtmlSender">
<property name="javaMailSender" ref="sender" />
</bean>
<bean id="temlateSender" class="com.springmail.demo3.TemplateSender">
<property name="javaMailSender" ref="sender" />
</bean>
<!-- freemarker支持 -->
<bean id="freemarkerCfg" class="org.springframework.ui.freemarker.FreeMarkerConfigurationFactoryBean">
</bean>
</beans>
主要代码:实现发送附件到指定邮件
public void doSend() throws MessagingException, UnsupportedEncodingException{
//邮件里面的信息
MimeMessage mm=javaMailSender.createMimeMessage();
//含添加附件的方法true代表有附件
MimeMessageHelper mmh=new MimeMessageHelper(mm,true);
File file1=new File("attachment/english.txt");
File file2=new File("attachment/中文.txt");
//添加附件
mmh.addAttachment(file1.getName(), file1);
mmh.addAttachment(MimeUtility.encodeText(file2.getName()), file2);
mmh.setFrom("*******@qq.com");//发件者和配置文件的userName保持一致
mmh.setTo("********@qq.com");//收件者
mmh.setSubject("languge");//设置邮件的主题
mmh.setSentDate(new Date());
mmh.setText("邮件正文");
javaMailSender.send(mm);
}
标签:
原文地址:http://www.cnblogs.com/shumengru/p/5426489.html