具體背景就不說了,可以網上搜索相關知識,或者直接看Sping MailSender的官坊網頁。這里就直接實戰了(Java實現異步發送電子郵件,包含中文無亂碼)。
Maven:
<dependency> <groupId>com.sun.mail</groupId> <artifactId>javax.mail</artifactId> <version>1.5.0</version> </dependency>
ApplicationContext.xml:
<!-- SET default mail properties --> <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl"> <property name="host" value="smtp.sina.com"/> <property name="protocol" value="smtp" /> <!-- 465 for Gamil --> <property name="port" value="25"/> <property name="username" value="xxx@sina.com"/> <property name="password" value="xxx"/> <property name="javaMailProperties"> <props> <prop key="mail.transport.protocol">smtp</prop> <prop key="mail.smtp.auth">true</prop> <!-- true for Gamil --> <prop key="mail.smtp.starttls.enable">false</prop> <prop key="mail.debug">true</prop> </props> </property> </bean> <!--Asyn send Eamil--> <bean id="taskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor"> <property name="corePoolSize" value="10"/> <property name="maxPoolSize" value="30"/> </bean> <!-- You can have some pre-configured messagess also which are ready to send --> <bean id="preConfiguredMessage" class="org.springframework.mail.SimpleMailMessage"> <property name="to" value="xxx@gmail.com"></property> <property name="from" value="xxx@sina.com"></property> <property name="subject" value="Test email from sina."/> </bean>
Email實體類:
package com.xxx; import java.io.Serializable; /** * @author * */ public class ApplicationEmail implements Serializable { public String getAddressee() { return addressee; } public void setAddressee(String addressee) { this.addressee = addressee; } public String getCc() { return cc; } public void setCc(String cc) { this.cc = cc; } public String getSubject() { return subject; } public void setSubject(String subject) { this.subject = subject; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } /**收件人**/ private String addressee; /**抄送給**/ private String cc; /**郵件主題**/ private String subject; /**郵件內容**/ private String content; /**附件**/ //private MultipartFile[] attachment = new MultipartFile[0]; }
異步郵件發送封裝類:
package com.xxx; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.Properties; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeUtility; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.core.task.TaskExecutor; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.stereotype.Service; import com.xxx.Mailer; /** * @author * */ @Service public class ApplicationMailer implements Mailer { @Autowired private JavaMailSender mailSender; @Autowired private TaskExecutor taskExecutor; @Autowired private SimpleMailMessage preConfiguredMessage; /** * 同步發送郵件 * * @param email * @throws MessagingException * @throws IOException */ public void sendMailBySynchronizationMode(ApplicationEmail email) throws MessagingException, IOException { Session session=Session.getDefaultInstance(new Properties()); MimeMessage mime= new MimeMessage(session); MimeMessageHelper helper = new MimeMessageHelper(mime, true, "utf-8"); helper.setFrom("xxx@sina.com");//發件人 helper.setTo(InternetAddress.parse(email.getAddressee()));//收件人 //helper.setBcc("administrator@chinaptp.com");//暗送 helper.setReplyTo("xxx@sina.com");//回復到 helper.setSubject(email.getSubject());//郵件主題 helper.setText(email.getContent(), true);//true表示設定html格式 mailSender.send(mime); } /** * 異步發送郵件 * * @param email */ public void sendMailByAsynchronousMode(final ApplicationEmail email){ taskExecutor.execute(new Runnable(){ public void run(){ try { sendMailBySynchronizationMode(email); } catch (Exception e) { } } }); } } public interface Mailer { public void sendMailByAsynchronousMode(final ApplicationEmail email); }
調用Service異步發送郵件:
@Autowired private Mailer mailer; //這是要異步發送郵件 ApplicationEmail email = new ApplicationEmail(); email.setAddressee("xxx@gmail.com"); email.setSubject("測試郵件有一份"); email.setContent("這個是內容html內容"); mailer.sendMailByAsynchronousMode(email);
這里實現異步使用的是Task Execution,也可以用異步注解@Async,或者JMS(需要J2EE環境);如果需要調度可以用Quartz(使用場景如:每天2:00需要批量給會員發郵件)
如果要實現高可靠的高並發的異步郵件發送,可以用JMS或Queue,參考。
本文結束。(干貨分享:Spring和JavaMail發送郵件的經驗.pdf)