導入spring-context-support-4.0.5.RELEASE.jar相關jarjava
這裏能夠靈活配置發件郵箱服務器、發件郵箱端口、發件用戶名、密碼spring
若是系統發件服務器信息定死在properties中能夠在spring.xml中直接配置服務器
本文采用系統中動態配置發件信息服務器異步
<bean id="javaMailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl"> <property name="defaultEncoding" value="utf-8" /> <!-- <property name="host" value="${mail.host}" /> <property name="port" value="${mail.port}" /> <property name="username" value="${mail.fromAddress}" /> <property name="password" value="${mail.fromAddressPassword}" /> --> <property name="javaMailProperties"> <props> <prop key="mail.smtp.auth">true</prop> <!-- <prop key="mail.smtp.timeout">25000</prop> --> <!-- <prop key="mail.smtp.starttls.enable">true</prop> --> <prop key="mail.smtp.ssl.enable">true</prop> <prop key="mail.smtp.socketFactory.class">javax.net.ssl.SSLSocketFactory</prop> </props> </property> </bean>
採用freemarker 構建郵件的模板socket
採用spring線程池實現異步發送async
@Autowired private FreeMarkerConfigurer freemarkerConfig; @Autowired private JavaMailSenderImpl javaMailSender; @Autowired private TaskExecutor taskExecutor; /** * 發送郵件 * * @param smtpFromMail * 發件人郵箱 * @param smtpHost * SMTP服務器地址 * @param smtpPort * SMTP服務器端口 * @param smtpUsername * SMTP用戶名 * @param smtpPassword * SMTP密碼 * @param toMail * 收件人郵箱 * @param subject * 主題 * @param templatePath * 模板路徑 * @param model * 數據 * @param async * 是否異步 */ public void send(String smtpHost, Integer smtpPort, String smtpUsername, String smtpPassword, String toMail, String subject, String templatePath, Map<String, Object> model, boolean async) { Assert.hasText(smtpHost); Assert.notNull(smtpPort); Assert.hasText(smtpUsername); Assert.hasText(smtpPassword); Assert.hasText(toMail); Assert.hasText(subject); Assert.hasText(templatePath); try { //Setting setting = SettingUtils.get(); Configuration configuration = freemarkerConfig.getConfiguration(); Template template = configuration.getTemplate(templatePath); String text = FreeMarkerTemplateUtils.processTemplateIntoString(template, model); javaMailSender.setHost(smtpHost); javaMailSender.setPort(smtpPort); javaMailSender.setUsername(smtpUsername); javaMailSender.setPassword(smtpPassword); MimeMessage mimeMessage = javaMailSender.createMimeMessage(); MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, false, "utf-8"); mimeMessageHelper.setFrom(smtpUsername); mimeMessageHelper.setSubject(subject); mimeMessageHelper.setTo(toMail); mimeMessageHelper.setText(text, true); if (async) { addSendTask(mimeMessage); } else { javaMailSender.send(mimeMessage); } } catch (TemplateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (MessagingException e) { e.printStackTrace(); } } /** * 添加郵件發送任務 * * @param mimeMessage * MimeMessage */ private void addSendTask(final MimeMessage mimeMessage) { try { taskExecutor.execute(new Runnable() { public void run() { javaMailSender.send(mimeMessage); } }); } catch (Exception e) { e.printStackTrace(); } }