1. 创建邮件(MIME 带有附件和图片)
//private static SimpleMailMessage mailMessage;
private static JavaMailSender jms;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");
jms = (JavaMailSender) ac.getBean("mailSender");
// mailMessage = (SimpleMailMessage) ac.getBean("mailMessage");
}
public void test2() throws MessagingException{
MimeMessage mailMessage = jms.createMimeMessage();
//创建Helper实例并声明编码为UTF-8,true表示Multipart
MimeMessageHelper helper = new MimeMessageHelper(mailMessage, true, "UTF-8");
helper.setFrom("1210845252@qq.com");
helper.setTo("2472533550@qq.com");
helper.setSubject("A little miss");
helper.setText("<html><body >访问我的空间:" +
"<a href='http://764663532.qzone.qq.com ' target='_blank'>" +
"<img src='cid:logo'></a></body></html>",true);
//添加一个嵌入图片
helper.addInline("logo", new ClassPathResource("logo.jpg"));
//添加一个普通附件
helper.addAttachment("freedsd.jpg", new ClassPathResource("freedsd.jpg"));
helper.addAttachment("2.jpg", new ClassPathResource("2.jpg"));
//发送
jms.send(mailMessage);
}
2. 编写beans。xml; 定义mailSender Bean
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderI
mpl">
<property name="host" value="smtp.qq.com"/>
<property name="port" value="25"/>
<property name="username" value="1210845252@qq.com"/><!-- aa13799979999@163.com -->
<property name="password" value="aa1111111"/>
<property name="javaMailProperties">
<props>
<prop key="mail.smtp.auth">true</prop>
<prop key="mail.smtp.starttls.enable">true</prop>
<!-- <prop key="mail.smtp.socketFactory.class">javax.net.ssl.SSLSocketFactory</prop>
-->
</props>
</property>
</bean>