利用spring mail 发送带附件的邮件

1.核心代码

  我们使用spring的mail,最主要是调用JavaMailSender mailSender和Template template;对象,创建message对象和cc、to、from等

MimeMailService类

private JavaMailSender mailSender;

	private Template template;

	/**
	 * Spring的MailSender.
	 */
	public void setMailSender(JavaMailSender mailSender) {
		this.mailSender = mailSender;
	}

	/**
	 * 注入Freemarker引擎配置,构造Freemarker 邮件内容模板.
	 */
	public void setFreemarkerConfiguration(Configuration freemarkerConfiguration) throws IOException {
		// 根据freemarkerConfiguration的templateLoaderPath载入文件.
		template = freemarkerConfiguration.getTemplate("mailTemplate.ftl", DEFAULT_ENCODING);
	}

	/**
	 * 发送MIME格式的用户修改通知邮件.
	 * @param title 邮件名
	 * @param fileList 附件地址
	 * @return true/发送成功 false/发送失败
	 */
	public Boolean sendNotificationMail(String title, List<String> fileList) {
		try {
			// 创建message对象
			MimeMessage msg = mailSender.createMimeMessage();
			// 生成spring的helper类,赋值收件人、发件人、抄送、主题等
			MimeMessageHelper helper = new MimeMessageHelper(msg, true, DEFAULT_ENCODING);

			// 收件人
			helper.setTo(C.MAIL_TO);
			// helper.setCc("2027247644@qq.com");
			// 发件人
			helper.setFrom(C.MAIL_FROM);
			// 主题
			helper.setSubject(title + "日接客送客生成通知");

			// 使用Freemarker生成html格式内容,即mailTemplate.ftl的内容
			String content = generateContent(title);
			helper.setText(content, true);

			// 附件对象,添加进邮件helper内
			for (String fileUrl : fileList) {
				logger.info("接客送客生成:" + fileUrl);
				File file = new File(fileUrl);
				String fileNm = file.getName();
				helper.addAttachment(fileNm, file);
			}

			mailSender.send(msg);
			logger.info("HTML版邮件已发送至" + C.MAIL_TO);
			return true;
		} catch (MessagingException e) {
			logger.error("构造邮件失败", e);
			return false;
		} catch (Exception e) {
			logger.error("发送邮件失败", e);
			return false;
		}
	}

	/**
	 * 使用Freemarker生成html格式内容.
	 */
	@SuppressWarnings("unchecked")
	private String generateContent(String userName) throws MessagingException {

		try {
			Map context = Collections.singletonMap("userName", userName);
			return FreeMarkerTemplateUtils.processTemplateIntoString(template,
					context);
		} catch (IOException e) {
			logger.error("生成邮件内容失败, FreeMarker模板不存在", e);
			throw new MessagingException("FreeMarker模板不存在", e);
		} catch (TemplateException e) {
			logger.error("生成邮件内容失败, FreeMarker处理失败", e);
			throw new MessagingException("FreeMarker处理失败", e);
		}
	}

2.依赖的文件配置

applicationContext-email.xml

<!-- 邮件发送器 -->
	<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
		<property name="host" value="smtp.163.com" />
		<property name="username" value="cuidez@163.com" />
		<property name="password" value="???" />
		<property name="javaMailProperties">
			<props>
				<prop key="mail.smtp.auth">true</prop>
				<prop key="mail.debug">true</prop>   
				<!-- <prop key="mail.smtp.starttls.enable">true</prop> -->
				
			</props>
		</property>
	</bean>

	<!-- 文本邮件服务类 -->
	<!-- <bean id="simpleMailService" class="com.zy.email.SimpleMailService">
		<property name="mailSender" ref="mailSender" />
		<property name="textTemplate">
			<value><![CDATA[
			用戶%1$s在%2$tF被修改.
					System Administrator.
			]]></value>
		</property>
	</bean> -->

	<!-- MIME邮件服务类 -->
	<bean id="mimeMailService" class="com.zy.service.MimeMailService">
		<property name="mailSender" ref="mailSender" />
		<property name="freemarkerConfiguration" ref="freemarkerConfiguration"></property>
	</bean>

	<!-- 用于生成HTML邮件内容的Freemarker配置 -->
	<bean id="freemarkerConfiguration" class="org.springframework.ui.freemarker.FreeMarkerConfigurationFactoryBean">
		<property name="templateLoaderPath" value="classpath:/" />
	</bean>

mailTemplate.ftl(邮件模板)

<html>
<head>对账单生成通知</head>
<body>
	<h1>对账单${userName}已经生成,请查看附件!</h1>
</body>
</html>


3.程序入口

@Autowired
	public MimeMailService mimeMailService;
	
	public void execute(){
		List<String> list = new ArrayList<String>();
		list.add("d:/002.jpg");
		
		mimeMailService.sendNotificationMail("这是测试的title",list);
	}



类似的文章,请戳我

posted @ 2016-05-26 15:49  Bug开发攻城狮  阅读(217)  评论(0编辑  收藏  举报