使用Spring发送邮件

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);
}
}

你可能感兴趣的:(spring,J#)