1 Spring 提供的邮件发送工具类:
JavaMailSender :spring 提供的 发送邮件的接口 其对应的实现类是JavaMailSenderImpl
在service配置文件中配置了这个工具类:
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl"
p:host="${mail.smtp.host}"
p:port="${mail.smtp.port}"
p:username="${mail.smtp.username}"
p:password="${mail.smtp.password}" >
<property name="javaMailProperties">
<props>
<!-- 使用用户名和密码验证 -->
<prop key="mail.smtp.auth">false</prop>
</props>
</property>
</bean>
2 自己写的MailSenderServiceImp1 类:邮件发送service
1》解析邮件地址
2》读取邮件显示模板,并替换模板中的变量(如用户、主题等)
3》调用JavaMailSender的send()方法发送邮件。
根据模板文件内容发送邮件:
* 定义一个javaBean封装发送邮件所需要的相关信息:
public class EmailSender {
private String from;//来源
private String to;//去向
private String cc;
private String bcc;
private String content;//邮件内容
private String subject;//标题
private Map<String, String> param = new HashMap<String,String>();//参数
private List<File> attachments = new ArrayList<File>();//附件
......
}
* 编写一个工具类提供读取模板内容等方法
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import org.springframework.util.ResourceUtils;
/**
* Email工具类
*/
public class EmailSupport {
private String templet;//模板文件路径
private String encode;//编码
/**
* 解析email地址
*/
public InternetAddress[] parseAddress(String addressString){
if(addressString == null) return new InternetAddress[0];
try {
return InternetAddress.parse(addressString.replaceAll("\\s*[;,]\\s*", ","));
} catch (AddressException e) {
throw new UnsupportedOperationException("解析email address出錯!", e);
}
}
/**
* 读取模板
*/
protected String getTempletInner(){
StringBuffer buf = new StringBuffer();
FileInputStream instr = null;
InputStreamReader instrR = null;
BufferedReader bufferedReaderObj = null;
try {
File file = ResourceUtils.getFile(templet);
if(!file.exists())throw new UnsupportedOperationException("模板文件不存在==>file path:"+file.getPath());
instr = new FileInputStream(file);
instrR = new InputStreamReader(instr,this.getEncode());
bufferedReaderObj = new BufferedReader(instrR);
String strVal = "";
while ((strVal = bufferedReaderObj.readLine()) != null) {
buf.append(strVal);
}
} catch (Exception ex) {
throw new UnsupportedOperationException("讀取模板文件失敗!",ex);
} finally{
if(instr != null){
try {
instr.close();
} catch (IOException e) {
log.warn("fileInputStream can be not closed! \n\t"+e);
}
}
if(instrR != null){
try {
instrR.close();
} catch (IOException e) {
log.warn("InputStreamReader can be not closed! \n\t"+e);
}
}
if(bufferedReaderObj != null){
try {
bufferedReaderObj.close();
} catch (IOException e) {
log.warn("BufferedReader can be not closed! \n\t"+e);
}
}
}
return buf.toString();
}
public void setTemplet(String templet) {
this.templet = templet;
}
public String getTemplet() {
return templet;
}
public void setEncode(String encode) {
this.encode = encode;
}
public String getEncode() {
return encode;
}
}
* 邮件发送接口
import javax.mail.internet.InternetAddress;
/**
* 邮件服务类接口
*/
public interface MailSenderService{
/**
* 使用默認帳號發送Email
* @param to
* @param subject
* @param content
*/
public void send(String to,String subject,String content);
/**
* 發送簡單的Email
* @param emailSender
*/
public void send(EmailSender emailSender);
public InternetAddress[] parseAddress(String addressString);
}
* 邮件发送实现类
import java.io.File;
import java.util.Map;
import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
public class MailSenderServiceImp1 extends EmailSupport implements MailSenderService {
private JavaMailSender mailSender;
private String defaultFrom;
private int autoComminute = 50;
public void send(String to, String subject, String content) {
MimeMessage mime = mailSender.createMimeMessage();
SimpleMailMessage message = new SimpleMailMessage();
MimeMessageHelper helper;
try {
helper = new MimeMessageHelper(mime,true,"utf-8");
if(defaultFrom != null)helper.setFrom(defaultFrom);
helper.setTo(parseAddress(to));
helper.setSubject(subject);
String templet = getTempletInner();
helper.setText(content,true);
} catch (MessagingException e) {
throw new UnsupportedOperationException("發送郵件失敗!",e);
}
mailSender.send(mime);
}
public void send(EmailSender emailSender) {
InternetAddress[] toAddress = parseAddress(emailSender.getTo());
if(toAddress.length <= autoComminute){
sendWithEmailSender(emailSender, toAddress);
}else{
InternetAddress[] newAddress;
int count = (int)Math.ceil((float)toAddress.length / (float)autoComminute);
for(int i = 0; i < count; i++){
newAddress = new InternetAddress[autoComminute];
for(int j = i * autoComminute,n = 0; j < autoComminute; j++,n++){
if(j > toAddress.length ) break;
newAddress[n] = toAddress[j];
}
sendWithEmailSender(emailSender, newAddress);
}
}
}
private void sendWithEmailSender(EmailSender emailSender,InternetAddress[] toAddress){
MimeMessage mime = mailSender.createMimeMessage();
SimpleMailMessage message = new SimpleMailMessage();
MimeMessageHelper helper;
try {
helper = new MimeMessageHelper(mime,true,this.getEncode());
if(emailSender.getFrom()!=null){
helper.setFrom(emailSender.getFrom());
}else{
if(defaultFrom != null)helper.setFrom(defaultFrom);
}
helper.setTo(toAddress);
helper.setCc(parseAddress(emailSender.getCc()));
helper.setBcc(parseAddress(emailSender.getBcc()));
helper.setSubject(emailSender.getSubject());
String templet = getTempletInner();
templet = setParam(templet, emailSender.getParam());
templet = templet.replace("${title}", emailSender.getSubject()==null?"":emailSender.getSubject());
templet = templet.replace("${body}", emailSender.getContent()==null?"":emailSender.getContent());
helper.setText(templet,true);
for(File file: emailSender.getAttachments()){
helper.addAttachment(file.getName(), file);
}
} catch (MessagingException e) {
throw new UnsupportedOperationException("發送郵件失敗!",e);
}
mailSender.send(mime);
}
private String setParam(String templetInner, Map<String, String> param){
Object[] o = param.keySet().toArray();
for(int i = 0; i < o.length; i++){
String key = o[i].toString();
templetInner = templetInner.replace("${"+key+"}", param.get(key)==null?"": param.get(key));
}
return templetInner;
}
public void setMailSender(JavaMailSender mailSender) {
this.mailSender = mailSender;
}
public JavaMailSender getMailSender() {
return mailSender;
}
public void setDefaultFrom(String defaultFrom) {
this.defaultFrom = defaultFrom;
}
public String getDefaultFrom() {
return defaultFrom;
}
public void setAutoComminute(int autoComminute) {
this.autoComminute = autoComminute;
}
public int getAutoComminute() {
return autoComminute;
}
}
3 使用邮件发送
首先配置 MailSenderServiceImp1
<!-- 邮件模版 -->
<bean id="simpleMailSenderService" class="com.byd.erpit.tools.email.MailSenderServiceImp1"
p:defaultFrom="${mail.smtp.defaultFrom}"
p:encode="utf-8"
p:autoComminute="50"
p:templet="classpath:templet/simpleMailTemplet.html"
p:mailSender-ref="mailSender" />
发送email:
private void sendOrdermMail(String emailTitle,String content,String userName,String to){
if(userName.equals("")){
userName="客户";
}
try {
EmailSender emailSender = new EmailSender();
emailSender.setSubject(emailTitle);
emailSender.setTo(to);
Map param = emailSender.getParam();
param.put("title", emailTitle);
param.put("userName",userName);
param.put("content", content);
this.getSimpleEmailSenderService().send(emailSender);
} catch (Exception e) {
log.error("发送邮件出错!"+e);
}
}
JavaMailSender :spring 提供的 发送邮件的接口 其对应的实现类是JavaMailSenderImpl
在service配置文件中配置了这个工具类:
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl"
p:host="${mail.smtp.host}"
p:port="${mail.smtp.port}"
p:username="${mail.smtp.username}"
p:password="${mail.smtp.password}" >
<property name="javaMailProperties">
<props>
<!-- 使用用户名和密码验证 -->
<prop key="mail.smtp.auth">false</prop>
</props>
</property>
</bean>
2 自己写的MailSenderServiceImp1 类:邮件发送service
1》解析邮件地址
2》读取邮件显示模板,并替换模板中的变量(如用户、主题等)
3》调用JavaMailSender的send()方法发送邮件。
根据模板文件内容发送邮件:
* 定义一个javaBean封装发送邮件所需要的相关信息:
public class EmailSender {
private String from;//来源
private String to;//去向
private String cc;
private String bcc;
private String content;//邮件内容
private String subject;//标题
private Map<String, String> param = new HashMap<String,String>();//参数
private List<File> attachments = new ArrayList<File>();//附件
......
}
* 编写一个工具类提供读取模板内容等方法
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import org.springframework.util.ResourceUtils;
/**
* Email工具类
*/
public class EmailSupport {
private String templet;//模板文件路径
private String encode;//编码
/**
* 解析email地址
*/
public InternetAddress[] parseAddress(String addressString){
if(addressString == null) return new InternetAddress[0];
try {
return InternetAddress.parse(addressString.replaceAll("\\s*[;,]\\s*", ","));
} catch (AddressException e) {
throw new UnsupportedOperationException("解析email address出錯!", e);
}
}
/**
* 读取模板
*/
protected String getTempletInner(){
StringBuffer buf = new StringBuffer();
FileInputStream instr = null;
InputStreamReader instrR = null;
BufferedReader bufferedReaderObj = null;
try {
File file = ResourceUtils.getFile(templet);
if(!file.exists())throw new UnsupportedOperationException("模板文件不存在==>file path:"+file.getPath());
instr = new FileInputStream(file);
instrR = new InputStreamReader(instr,this.getEncode());
bufferedReaderObj = new BufferedReader(instrR);
String strVal = "";
while ((strVal = bufferedReaderObj.readLine()) != null) {
buf.append(strVal);
}
} catch (Exception ex) {
throw new UnsupportedOperationException("讀取模板文件失敗!",ex);
} finally{
if(instr != null){
try {
instr.close();
} catch (IOException e) {
log.warn("fileInputStream can be not closed! \n\t"+e);
}
}
if(instrR != null){
try {
instrR.close();
} catch (IOException e) {
log.warn("InputStreamReader can be not closed! \n\t"+e);
}
}
if(bufferedReaderObj != null){
try {
bufferedReaderObj.close();
} catch (IOException e) {
log.warn("BufferedReader can be not closed! \n\t"+e);
}
}
}
return buf.toString();
}
public void setTemplet(String templet) {
this.templet = templet;
}
public String getTemplet() {
return templet;
}
public void setEncode(String encode) {
this.encode = encode;
}
public String getEncode() {
return encode;
}
}
* 邮件发送接口
import javax.mail.internet.InternetAddress;
/**
* 邮件服务类接口
*/
public interface MailSenderService{
/**
* 使用默認帳號發送Email
* @param to
* @param subject
* @param content
*/
public void send(String to,String subject,String content);
/**
* 發送簡單的Email
* @param emailSender
*/
public void send(EmailSender emailSender);
public InternetAddress[] parseAddress(String addressString);
}
* 邮件发送实现类
import java.io.File;
import java.util.Map;
import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
public class MailSenderServiceImp1 extends EmailSupport implements MailSenderService {
private JavaMailSender mailSender;
private String defaultFrom;
private int autoComminute = 50;
public void send(String to, String subject, String content) {
MimeMessage mime = mailSender.createMimeMessage();
SimpleMailMessage message = new SimpleMailMessage();
MimeMessageHelper helper;
try {
helper = new MimeMessageHelper(mime,true,"utf-8");
if(defaultFrom != null)helper.setFrom(defaultFrom);
helper.setTo(parseAddress(to));
helper.setSubject(subject);
String templet = getTempletInner();
helper.setText(content,true);
} catch (MessagingException e) {
throw new UnsupportedOperationException("發送郵件失敗!",e);
}
mailSender.send(mime);
}
public void send(EmailSender emailSender) {
InternetAddress[] toAddress = parseAddress(emailSender.getTo());
if(toAddress.length <= autoComminute){
sendWithEmailSender(emailSender, toAddress);
}else{
InternetAddress[] newAddress;
int count = (int)Math.ceil((float)toAddress.length / (float)autoComminute);
for(int i = 0; i < count; i++){
newAddress = new InternetAddress[autoComminute];
for(int j = i * autoComminute,n = 0; j < autoComminute; j++,n++){
if(j > toAddress.length ) break;
newAddress[n] = toAddress[j];
}
sendWithEmailSender(emailSender, newAddress);
}
}
}
private void sendWithEmailSender(EmailSender emailSender,InternetAddress[] toAddress){
MimeMessage mime = mailSender.createMimeMessage();
SimpleMailMessage message = new SimpleMailMessage();
MimeMessageHelper helper;
try {
helper = new MimeMessageHelper(mime,true,this.getEncode());
if(emailSender.getFrom()!=null){
helper.setFrom(emailSender.getFrom());
}else{
if(defaultFrom != null)helper.setFrom(defaultFrom);
}
helper.setTo(toAddress);
helper.setCc(parseAddress(emailSender.getCc()));
helper.setBcc(parseAddress(emailSender.getBcc()));
helper.setSubject(emailSender.getSubject());
String templet = getTempletInner();
templet = setParam(templet, emailSender.getParam());
templet = templet.replace("${title}", emailSender.getSubject()==null?"":emailSender.getSubject());
templet = templet.replace("${body}", emailSender.getContent()==null?"":emailSender.getContent());
helper.setText(templet,true);
for(File file: emailSender.getAttachments()){
helper.addAttachment(file.getName(), file);
}
} catch (MessagingException e) {
throw new UnsupportedOperationException("發送郵件失敗!",e);
}
mailSender.send(mime);
}
private String setParam(String templetInner, Map<String, String> param){
Object[] o = param.keySet().toArray();
for(int i = 0; i < o.length; i++){
String key = o[i].toString();
templetInner = templetInner.replace("${"+key+"}", param.get(key)==null?"": param.get(key));
}
return templetInner;
}
public void setMailSender(JavaMailSender mailSender) {
this.mailSender = mailSender;
}
public JavaMailSender getMailSender() {
return mailSender;
}
public void setDefaultFrom(String defaultFrom) {
this.defaultFrom = defaultFrom;
}
public String getDefaultFrom() {
return defaultFrom;
}
public void setAutoComminute(int autoComminute) {
this.autoComminute = autoComminute;
}
public int getAutoComminute() {
return autoComminute;
}
}
3 使用邮件发送
首先配置 MailSenderServiceImp1
<!-- 邮件模版 -->
<bean id="simpleMailSenderService" class="com.byd.erpit.tools.email.MailSenderServiceImp1"
p:defaultFrom="${mail.smtp.defaultFrom}"
p:encode="utf-8"
p:autoComminute="50"
p:templet="classpath:templet/simpleMailTemplet.html"
p:mailSender-ref="mailSender" />
发送email:
private void sendOrdermMail(String emailTitle,String content,String userName,String to){
if(userName.equals("")){
userName="客户";
}
try {
EmailSender emailSender = new EmailSender();
emailSender.setSubject(emailTitle);
emailSender.setTo(to);
Map param = emailSender.getParam();
param.put("title", emailTitle);
param.put("userName",userName);
param.put("content", content);
this.getSimpleEmailSenderService().send(emailSender);
} catch (Exception e) {
log.error("发送邮件出错!"+e);
}
}
发表评论
-
仿百度文库文档播放效果
2011-06-22 16:58 1027仿百度文库文档播放效果 -
抽象类和接口
2011-04-15 10:56 627两者相似之处在于:抽象类和接口都不能被实例化,两种都是java ... -
java打印API详解
2011-04-07 18:03 877参见附件! -
java class文件反编译小工具
2011-04-06 15:04 679参见附件! -
网页转PDF简单方案
2011-03-02 14:20 1983给定一个页面路径,先要求将此路径的内容直接转换为pdf文件。 ... -
Eclipse调试常用技巧
2011-02-24 10:31 5741、 条件断点 断 ... -
tomact 1
2011-02-19 13:07 0fdsafds -
java操作excel-POI
2010-12-27 14:21 692Apache POI HSSF和XSSF读写EXCEL总结 ... -
htmlToPDF
2010-12-06 23:43 0............... -
java操作word-jacob
2010-12-06 17:03 603参见附件。 -
简单文件上传工具类
2010-12-06 15:44 1031使用org.apache.commons.fileupl ... -
简单自定义分页标签
2010-12-06 14:07 572相关内容参见附件。 -
web在线用户简单实现
2010-12-06 11:11 1211◆ 创建一个静态工厂类保存在线用户,示例代码如下: publi ...
相关推荐
通过以上步骤,你就可以在Java应用中使用Spring发送邮件了。当然,实际的邮件发送可能更复杂,涉及HTML内容、附件、多部分消息等,可以使用`MimeMessage`和`MimeMessageHelper`类来构建复杂的邮件结构。例如,添加...
下面将详细介绍如何使用Spring发送邮件。 首先,我们需要在项目中引入Spring的邮件支持。这通常通过添加`spring-context-support`依赖来完成,该依赖包含了处理邮件发送所需的类。在Maven项目中,可以在pom.xml文件...
和上面对比,这次发送邮件使用 MimeMessageHelper 类。MimeMessageHelper 支持发送复杂邮件模板,支持文本、附件、HTML、图片等,接下来我们会继续使用。 (3)发送带附件的邮件 在 MailService 添加 ...
Spring框架提供了一种优雅的方式来处理这个任务,它整合了JavaMailSender接口和JavaMail API,使得在Java应用程序中发送邮件变得更加简单。让我们深入探讨这个主题。 首先,JavaMail API是Java用来处理邮件收发的...
本教程将详细讲解如何使用Spring发送邮件,以及在遇到问题时如何排查。 首先,我们需要在Spring项目中引入邮件服务相关的依赖。在Maven项目中,可以在pom.xml文件中添加如下依赖: ```xml <groupId>org.spring...
标题 "Spring 使用163发邮件带附件" 涉及到的是在Java开发中,使用Spring框架发送电子邮件,特别是包含附件的邮件。这通常在系统需要自动化通知、报告发送或者用户验证过程中非常常见。Spring提供了JavaMailSender...
在IT行业中,Spring框架是Java开发中的一个关键组件,它提供了丰富的...对于那些需要发送大量或定期邮件的应用,还可以考虑使用邮件队列服务,如Amazon SES或SendGrid,配合Spring进行集成,实现高效、可靠的邮件发送。
在IT行业中,Spring框架是Java开发中的一个核心组件,它为构建高质量的、可维护的、面向服务的软件提供了强大的支持。...通过阅读和理解这个例子,你可以掌握在实际项目中使用Spring发送邮件的关键步骤。
使用Spring发送邮件的基本步骤如下: 1. 添加Spring核心库和相关的邮件发送库(如JavaMail API)到项目依赖中。 2. 在Spring配置文件(如`email-163.xml`)中配置邮件服务器的相关信息,如用户名、密码、SMTP服务器...
要使用Spring发送邮件,我们需要进行以下步骤: 1. **配置JavaMailSender**:在Spring的配置文件中,我们需要配置`JavaMailSender`的实现,例如`JavaMailSenderImpl`。配置项包括SMTP服务器地址、端口、用户名、...
从提供的文件列表中,我们可以推测`spring发送邮件.md`可能是一个Markdown格式的文档,详细讲解了如何配置和使用Spring发送邮件,而`1.png`、`2.png`和`3.png`可能是相关的截图,帮助读者更好地理解和学习这一过程。...
同时,如果你需要发送的邮件具有模板,可以考虑使用Spring的`Thymeleaf`或者其他模板引擎来动态生成邮件内容。 总的来说,Spring集成邮件服务使得在Java应用中发送邮件变得简单且灵活。通过合理的配置和编程,你...
在本文中,我们将深入探讨如何使用Spring框架实现邮件发送功能,特别关注SSM(Spring、...通过这个教程,新手可以快速掌握在Java应用中使用Spring发送邮件的基本技能,无论是普通的文本邮件还是富文本的HTML邮件。
接下来,我们将介绍如何使用Spring发送不同类型的邮件: 1. **发送纯文本邮件**: 要发送纯文本邮件,你可以创建一个`SimpleMailMessage`对象,设置发件人、收件人、主题和正文,然后调用`JavaMailSender`的`send...
本项目聚焦于使用Spring Boot来开发一个支持多附件邮件发送的微服务平台。这个平台可以方便地集成到各种业务场景中,例如发送报告、通知或者用户验证邮件。 首先,我们需要了解Spring Boot的邮件服务模块——`...
本文将详细介绍如何使用Spring发送邮件,包括配置JavaMailSenderImpl以及编写发送邮件的代码。 首先,Spring的核心邮件发送抽象是MailSender接口。这个接口定义了发送邮件的基本操作,而它的具体实现是...
总结来说,Spring发送邮件需要`spring-context`、`spring-context-support`、`java-mail`、`javax.activation`这些核心库,以及可能需要的测试库`junit`。理解和掌握这些库的作用及如何配置它们,对于实现Spring中的...