Spring邮件服务之附件:Maven + Spring SMTP Mail With Attachment (二)

2014-11-24 08:17:15 · 作者: · 浏览: 1
和FileSystemResource都实现了这个接口
*/
messageHelper.addAttachment(file.getFilename(), file); //添加附件
javaMailSender.send(mimeMessage); //发送附件邮件

} catch (Exception e) {System.out.println("异常信息:" + e);}
}
//Spring 依赖注入
public void setSimpleMailMessage(SimpleMailMessage simpleMailMessage) {
this.simpleMailMessage = simpleMailMessage;
}
//Spring 依赖注入
public void setJavaMailSender(JavaMailSender javaMailSender) {
this.javaMailSender = javaMailSender;
}
}


Junit Test:EmailTest.java

package com.fancy.test;

import junit.framework.TestCase;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.fancy.util.Email;
/**
* -----------------------------------------
* @文件: EmailTest.java
* @作者: fancy
* @邮箱: fancydeepin@yeah.net
* @时间: 2012-6-12
* @描述: Junit测试,运行将发送一封email
* -----------------------------------------
*/
public class EmailTest extends TestCase {

public void testSendMail() {
ApplicationContext context = new ClassPathXmlApplicationContext("spring-smtp-mail-attachment.xml");
Email mail = (Email)context.getBean("simpleMail");
mail.sendMail("Spring SMTP Mail With Attachment Subject", "Spring SMTP Mail With Attachment Text Content", "fancyzero@yeah.net");
//mail.sendMail("标题", "内容", "收件人邮箱");
}

}

pom.xml

http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
com.fancy
spring-mail-attachment-example
1.0
jar
spring-mail-attachment-example
http://maven.apache.org

UTF-8




org.springframework
spring
2.5.6



javax.mail
mail
1.4.4



junit
junit
4.1
test




运行一下 Junit 的 EmailTest.java 收到邮件:

\
\
\

\


测试完成,英文、中文、压缩包 附件都能正常发送和下载。www.2cto.com


下面附上 Spring 官方文档对Attachment的示例:

24.3.1.1 Attachments
The following example shows you how to use the MimeMessageHelper to send an email along with a single JPEG image attachment.

JavaMailSenderImpl sender = new JavaMailSenderImpl();
sender.setHost("mail.host.com");

MimeMessage message = sender.createMimeMessage();

// use the true flag to indicate you need a multipart message
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setTo("test@host.com");

helper.setText("Check out this image!");

// let's attach the infamous windows Sample file (this time copied to c:/)
FileSystemResource file = new FileSystemResource(new File("c:/Sample.jpg"));
helper.addAttachment("CoolImage.jpg", file);

sender.send(message);
作者:fancydeepin