您的位置:首页 > 编程语言 > Java开发

使用 SPRING 邮件发送器发送邮件 JavaMailSenderImpl

2014-06-11 17:29 465 查看
Spring 内置了一个邮件发送器 JavaMailSenderImpl,可以用它来发送文本邮件、HTML 邮件并且发送附件。
具体详细的功能和简介这里就不多说了,直接带大家做一遍:
一段可运行的代码比说很多废话强得多
S1 :首先要保证项目当中使用 SPRING

Spring官网: http://projects.spring.io/spring-framework/

S2:配置邮件参数文件 jdbc.properties(你懂的...偷个懒)

#配置服务器邮件账号信息
#服务器
mail.smtp.host=smtp.xxx.com
#是否需要验证密码
mail.smtp.auth=true
#超时时间
mail.smtp.timeout=25000
#发件人信箱
mail.smtp.from=xxx@163.com
#用户名
mail.smtp.username=xxx@163.com
#密码
mail.smtp.password=123456


S3:配置 applicationContext.xml

首先配置配置文件路径,这里配置的是 jdbc.properties,然后配置 JavaMailSenderImpl,参数从 jdbc.properties 当中获得

<!-- in-memory database and a datasource -->
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="classpath:jdbc.properties" />

<!-- 配置邮件 senderbean -->
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value="${mail.smtp.host}"></property>
<property name="javaMailProperties" >
<props>
<prop key="mail.smtp.auth">${mail.smtp.auth}</prop>
<prop key="mail.smtp.timeout">${mail.smtp.timeout}</prop>
</props>
</property>
<property name="username" value="${mail.smtp.username}"></property>
<property name="password" value="${mail.smtp.password}"></property>
</bean>


S4:编写 ACTION 代码,实现邮件发送功能,这里还附加了一个附件,如果文件是从前台传递过来的可以用的上 ACTION 当中的参数,这里只是做了一个模拟。将上述代码拷贝到项目当中即可运行。

/**
********************************************************************************************
* @ClassName: ForcastAction
* @Description: TODO
* @author ZhouQian
* @date 2014-6-11-上午11:00:34
********************************************************************************************
*/
public class ForcastAction extends ActionSupport implements ServletRequestAware, ServletResponseAware, SessionAware {
private static final long serialVersionUID = 1L;
private HttpServletRequest request;
private HttpServletResponse response;
// struts mapsession ,key value
private Map<String, Object> session;

// 邮件发送器
private JavaMailSenderImpl mailSender;
// 设定上传文件路径
private static final String FOLDER_NAME = "/upload/";

// 上传的附件和附件名称
private File[] attachment;
private String[] attachmentFileName;

/**
* 邮件发送 接口用于向测试用户发送邮件 后期可能采用定时器进行邮件发送
*/
public void sendEmail() {
// 邮件POJO 对象
MailPojo mailPojo = new MailPojo();
MimeMessage m = mailSender.createMimeMessage();

// 构造附件
String path = "jsp/theme/analyser/hero.html";
path = request.getSession().getServletContext().getRealPath("/") + path;
attachment = new File[1];
attachment[0] = new File(path);
attachmentFileName = new String[1];
attachmentFileName[0] = "hero.html";
try {
MimeMessageHelper helper = new MimeMessageHelper(m, true, "UTF-8");
// 设置收件人
helper.setTo("xxx@163.com");
// 设置抄送
//			helper.setCc("");
// 设置发件人
helper.setFrom("xxx@163.com");
// 设置暗送
//			helper.setBcc("");
// 设置主题
helper.setSubject("测试邮件!");
// 设置 HTML 内容
helper.setText("这只是一封测试邮件!如果你收到的话说明我已经发送成功了!");

// 保存附件,这里做一个 copy 只是为了防止上传文件丢失
attachment = saveFiles(attachment, attachmentFileName);
for (int i = 0; attachment != null && i < attachment.length; i++) {
File file = attachment[i];
// 附件源
FileSystemResource resource = new FileSystemResource(file);
helper.addAttachment(attachmentFileName[i], resource);

// mail 对象填充
AttachmentPojo attachmentPojo = new AttachmentPojo();
attachmentPojo.setFilename(attachmentFileName[i]);
attachmentPojo.setFilepath(file.getAbsolutePath());
mailPojo.getAttachmentPojos().add(attachmentPojo);
}

// 进行邮件发送和邮件持久类的状态设定z
mailSender.send(m);
mailPojo.setSent(true);
System.out.println("邮件发送成功!");

} catch (Exception e) {
e.printStackTrace();
mailPojo.setSent(false);
// TODO: handle exception
}
//		dao.create(mail) 进行持久化,如果有这一步的话
}

/**
* struts 2 会将文件自动上传到临时文件夹中,Action运行完毕后临时文件会被自动删除 因此需要将文件复制到 /upload 文件夹下
*
* @param files
* @param names
* @return
*/
public File[] saveFiles(File[] files, String[] names) {
if (files == null)
return null;
File root = new File(ServletActionContext.getServletContext().getRealPath(FOLDER_NAME));
File[] destinies = new File[files.length];
for (int i = 0; i < files.length; i++) {
File file = files[i];
File destiny = new File(root, names[i]);
destinies[i] = destiny;
copyFile(file, destiny);
}
return destinies;
}

/**
* 复制单个文件
*
* @param from
* @param to
*/
public void copyFile(File from, File to) {
InputStream ins = null;
OutputStream ous = null;
try {
// 创建所有上级文件夹
to.getParentFile().mkdirs();
ins = new FileInputStream(from);
ous = new FileOutputStream(to);
byte[] b = new byte[1024];
int len;
while ((len = ins.read(b)) != -1) {
ous.write(b, 0, len);
}
} catch (Exception e) {
// TODO: handle exception
} finally {
if (ous != null)
try {
ous.close();
} catch (Exception e) {
e.printStackTrace();
}
if (ins != null)
try {
ins.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

public void setServletResponse(HttpServletResponse httpservletresponse) {
this.response = httpservletresponse;
}

public void setServletRequest(HttpServletRequest httpservletrequest) {
this.request = httpservletrequest;
}

public void setSession(Map<String, Object> session) {
this.session = session;
}

public JavaMailSenderImpl getMailSender() {
return mailSender;
}

public void setMailSender(JavaMailSenderImpl mailSender) {
this.mailSender = mailSender;
}

public File[] getAttachment() {
return attachment;
}

public void setAttachment(File[] attachment) {
this.attachment = attachment;
}

public String[] getAttachmentFileName() {
return attachmentFileName;
}

public void setAttachmentFileName(String[] attachmentFileName) {
this.attachmentFileName = attachmentFileName;
}

}


如果大家有不明白的可以留言问我,一同进步
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息