使用springMail发送带附件的email

使用spring Mail 发送带email的邮件,大大的减小了使用java email发送邮件的麻烦,
spring提供了一个MimeMessageHelper的助手类来完成发送附件的功能

 

package mail;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;

public class Main {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		ApplicationContext context = new ClassPathXmlApplicationContext("config.xml");
		JavaMailSender mailSender= (JavaMailSender) context.getBean("mailSender");
		MimeMessage mime = mailSender.createMimeMessage();
		MimeMessageHelper helper;
		try {
			helper = new MimeMessageHelper(mime,true,"utf-8");
			helper.setFrom("[email protected]");
			helper.setTo("[email protected]");
			helper.setSubject(" 测试spring Mail的附件功能");
			//需要将附件显示在html中
			//在标签中用cid:xx 标记,使用helper.addInline()方法添加
			helper.setText("<html><body>javaeye是个好网站:<br>"+
					"<a href='http://www.iteye.com'>" +
					"<img src='cid:logo'></a></body></html>",true);
			helper.addInline("logo", new ClassPathResource("logo.gif"));
			helper.addAttachment("javaeye.gif", new ClassPathResource("javaeye.gif"));
		} catch (MessagingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	
		mailSender.send(mime);
	}

}

对应的config.xml ,同发送普通邮件的一样

 

你可能感兴趣的:(spring,html,xml,Gmail)