`
TRAMP_ZZY
  • 浏览: 131985 次
社区版块
存档分类
最新评论

JavaMail Spring Mail支持

阅读更多
1. 普通的JavaMail 发送和接受邮件
public class TestMail {

	public static void main(String[] args) {
		Transport transport = null;
		
		Properties prop = new Properties();
		prop.put("mail.smtp.host", "smtp.163.com");
		prop.put("mail.smtp.auth", true);
		
		Authenticator auth = new Authenticator() {
			@Override
			protected PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication("tramp0524@163.com", "tramp");
			}
		};
		
		Session session = Session.getDefaultInstance(prop, auth);
		Message msg = new MimeMessage(session);
		try {
			msg.setFrom(new InternetAddress("tramp0524@163.com"));
			msg.setRecipient(Message.RecipientType.TO, new InternetAddress("250823912@qq.com"));
			msg.setSubject("Test Mail");
			msg.setSentDate(new Date());
			msg.setText("how are you~");
			
			transport = session.getTransport("smtp");
			transport.send(msg);
			System.out.println("send success");
		} catch (AddressException e) {
			e.printStackTrace();
		} catch (MessagingException e) {
			e.printStackTrace();
		} finally {
			try {
				transport.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}

public class JavaMailSSL {

	public static void main(String argv[]) throws Exception {
		Properties props = new Properties();
		Session session = Session.getDefaultInstance(props);
		URLName urln = new URLName("pop3", "pop.163.com", 110, null,
				"tramp0524@163.com", "tramp");
		/*URLName urln = new URLName("pop3s", "pop.163.com", 995, null,
				"tramp0524@163.com", "tramp");*/
		Store store = session.getStore(urln);
		
		Folder inbox = null;
		try {
			store.connect();
			inbox = store.getFolder("INBOX");
			inbox.open(Folder.READ_ONLY);
			FetchProfile profile = new FetchProfile();
			profile.add(FetchProfile.Item.ENVELOPE);
			Message[] msgs = inbox.getMessages();
			inbox.fetch(msgs, profile);
			System.out.println("收件箱的邮件数:" + msgs.length);
			for (int i = 0; i < msgs.length; i++) {
				String from = msgs[i].getFrom()[0].toString();
				InternetAddress ia = new InternetAddress(from);
				System.out.println("-----------------------------");
				System.out.println("发送者:" + ia.getPersonal() + "/"
						+ ia.getAddress());
				System.out.println("标题:" + msgs[i].getSubject());
				System.out.println("大小:" + msgs[i].getSize());
				System.out.println("时间:" + msgs[i].getSentDate());
			}
		} finally {
			try {
				inbox.close(false);
			} catch (Exception e) {
			}
			try {
				store.close();
			} catch (Exception e) {
			}
		}
	}

	protected static String decodeText(String text)
			throws UnsupportedEncodingException {
		if (text == null)
			return null;
		if (text.startsWith("=?GB") || text.startsWith("=?gb"))
			text = MimeUtility.decodeText(text);
		else
			text = new String(text.getBytes("ISO8859_1"));
		return text;
	}

}

2. Spring Mail 集成
@Service
public class MailService {

	@Autowired
	private JavaMailSender javaMailSender;
	@Autowired
	private FreeMarkerConfigurer freeMarkerConfigurer;
	@Autowired
	private TaskExecutor taskExecutor;
	
	public void sendSimpleMail() {
		SimpleMailMessage msg = new SimpleMailMessage();
		msg.setFrom("tramp0524@163.com");
		msg.setTo("250823912@qq.com");
		msg.setReplyTo("tramp0524@163.com");
		// 抄送
		msg.setCc("tramp0524@163.com");
		msg.setSubject("success login");
		msg.setText("nice to meet you !!!");
		this.javaMailSender.send(msg);
	}
	
	public void sendHtmlMail(String userName) throws MessagingException {
		MimeMessage msg = this.javaMailSender.createMimeMessage();
		MimeMessageHelper helper = new MimeMessageHelper(msg, false, "utf-8");
		helper.setFrom("tramp0524@163.com");
		helper.setTo("250823912@qq.com");
		helper.setSubject("注册成功");
		String htmlText = "<html><head>"
				+ "<meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\">"
				+ "</head><body>" + "恭喜,您在IBlog已经注册成功!您的用户ID为:"
				+ "<font size='20' size='30'>" + userName + "</font>"
				+ "</body></html>";
		// true show it is a mail of html
		helper.setText(htmlText, true);
		this.javaMailSender.send(msg);
	}
	
	public void sendInlineMail() throws MessagingException {
		MimeMessage msg = this.javaMailSender.createMimeMessage();
		MimeMessageHelper helper = new MimeMessageHelper(msg, true, "utf-8");
		helper.setFrom("tramp0524@163.com");
		helper.setTo("250823912@qq.com");
		helper.setSubject("注册成功");
		String htmlText = "<html><head>"
				+ "<meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\">"
				+ "</head><body>" + "欢迎访问IBlog论坛!</hr>"
				+ "<div><img src=\"cid:img01\"></img></div>" + "</body></html>";
		// true show it is a mail of html
		helper.setText(htmlText, true);
		ClassPathResource resource = new ClassPathResource("1382946922292.jpg");
		helper.addInline("img01", resource);
		
		this.javaMailSender.send(msg);
			
	}
	
	public void sendAttachmentMail() throws MessagingException, IOException {
		MimeMessage msg = javaMailSender.createMimeMessage();
		MimeMessageHelper helper = new MimeMessageHelper(msg, true, "utf-8");
		helper.setFrom("tramp0524@163.com");
		helper.setTo("250823912@qq.com");
		helper.setSubject("注册成功");
		helper.setText("欢迎访问宝宝淘论坛!");
		ClassPathResource file1 = new ClassPathResource("bbt.zip");
		helper.addAttachment("file01.zip", file1.getFile());
		ClassPathResource file2 = new ClassPathResource("file.doc");
		helper.addAttachment("file02.doc", file2.getFile());
		javaMailSender.send(msg);
	}
	
	// 发送双版本邮件
	public void sendAlternativeMail() throws Exception {
		MimeMessagePreparator mmp = new MimeMessagePreparator() {
			public void prepare(MimeMessage msg) throws Exception {
				MimeMessageHelper helper = new MimeMessageHelper(msg, true,
						"utf-8");
				helper.setFrom("tramp0524@163.com");
				helper.setTo("250823912@qq.com");
				helper.setSubject("注册成功");

				MimeMultipart mmPart = new MimeMultipart("alternative");
				msg.setContent(mmPart);

				BodyPart plainTextPart = new MimeBodyPart();
				plainTextPart.setText("欢迎访问宝宝淘论坛!");
				mmPart.addBodyPart(plainTextPart);

				BodyPart htmlPart = new MimeBodyPart();
				String htmlText = "<html><head>"
						+ "<meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\">"
						+ "</head><body><font size='20' size='30'>"
						+ "欢迎访问宝宝淘论坛</font>" + "</body></html>";
				htmlPart.setContent(htmlText, "text/html;charset=utf-8");
				mmPart.addBodyPart(htmlPart);
			}
		};
		javaMailSender.send(mmp);
	}
	
	public void sendTemplateMail(String userId) throws MessagingException {
		MimeMessage msg = javaMailSender.createMimeMessage();
		MimeMessageHelper helper = new MimeMessageHelper(msg, false, "utf-8");
		helper.setFrom("tramp0524@163.com");
		helper.setTo("250823912@qq.com");
		helper.setSubject("注册成功:基于模板");
		String htmlText = getMailContent(userId);
		helper.setText(htmlText, true);
		javaMailSender.send(msg);
	}
	
	public String getMailContent(String userId) {
		String text = null;
		try {
			Template template = this.freeMarkerConfigurer.getConfiguration().getTemplate("registerUser.ftl");
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("userId", userId);
			
			text = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return text;
	}
	
	public void sendAsyncMail(final String userId) {
		taskExecutor.execute(new Runnable() {
			public void run() {
				try {
					sendTemplateMail(userId);
					System.out.println("邮件发送成功!");
				} catch (Exception e) {
					System.out.println("邮件发送失败!,异常信息:" + e.getMessage());
				}
			}
		});
	}
}


<!-- spirng javamail config -->
	<bean id="javaMailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl"
		p:host="smtp.163.com"
		p:protocol="smtp"
		p:defaultEncoding="utf8"
		p:username="tramp0524@163.com"
		p:password="tramp">
		<property name="javaMailProperties">
			<props>
				<prop key="mail.smtp.auth">true</prop>
			</props>
		</property>
	</bean>
	<!-- freemarker -->
	<bean id="freeMarkerConfigurer" 
		class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer"
		p:templateLoaderPath="classpath:template/">
		<property name="freemarkerSettings">
			<props>
				<prop key="template_update_delay">1800</prop>
				<prop key="default_encoding">UTF-8</prop>
				<prop key="locale">zh_CN</prop>
			</props>
		</property>
	</bean>
	
	<!-- 异步执行器 -->
	<bean id="taskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor"
		p:corePoolSize="10"
		p:maxPoolSize="30" />
分享到:
评论

相关推荐

    SpringMail发邮件

    SpringMail.rar SpringMail发邮件

    thymeleafexamples-springmail-3.0-master.zip

    You can deploy the application any Java servlet container or executing the application on an embedded Tomcat 7 with mvn tomcat7:run (the application will be at http://localhost:8080/springmail/).

    JavaMail实现源代码和jar包

    这是 http://blog.csdn.net/y353027520dx/article/details/42418117 文章的源代码和使用的jar包,解压后就能直接运行,希望大家多多支持啊

    spring各种邮件发送

    为了使用JavaMail中的一些特色, 比如MIME类型的信件, Spring提供了MailSender的一个子接口, 即org.springframework.mail.javamail.JavaMailSender。Spring还提供了一个回调接口org.springframework.mail.javamail....

    spring结合javamail开发文档

    先详细介绍javamail的开发,之后结合spring框架,包含一般邮件,html邮件,附件,音乐附件等开发文档,精品文档27页,参考文中实例即可完美开发。

    Learning.Spring.Application.Development.1783987367

    Title: Learning Spring Application Development Author: Ravi Kant Soni Length: 492 pages Edition: 1 Language: English Publisher: Packt Publishing - ...Chapter 8: Integrating Javamail And Jms With Spring

    java 发送邮件 spring发送邮件Mail

    java 发送邮件 spring发送邮件Mail

    SpringBoot整合邮箱JavaMail

    SpringBoot整合JavaMail功能,使用的是Spring自带的发送邮件功能,本Demo以qq邮箱为服务器做的测试,完成了纯文本发送、html发送、嵌入图片、带有附件等的封装,如有不足欢迎交流

    Java Mail封装的Jar包

    封装了一个java mail的jar包,只需设置邮件的基本信息 就可发邮件: //这个类主要是设置邮件 MailSenderInfo mailInfo = new MailSenderInfo(); mailInfo.setMailServerHost("smtp.163.com"); mailInfo....

    spring集成邮件服务

    spring集成邮件服务,以前做的demo,希望对大有所有帮助!!

    javamail的封装

    自定义的不依赖spring的类似spring的邮件发送源码,jar和demo

    Spring Boot整合JavaMailSender发送电子邮件

    Spring提供了非常好用的JavaMailSender接口实现邮件发送。在Spring Boot的Starter模块中也为此提供了自动化配置。下面通过实例看看如何在Spring Boot中使用JavaMailSender发送邮件。

    thymeleafexamples-springmail:SpringMail-Thymeleaf网站上的“带有Thymeleaf的Spring丰富HTML电子邮件”文章的配套应用程序

    Thymeleaf 3示例:Spring Mail 这是一个示例应用程序,显示了如何使用Spring和Thymeleaf编写和发送动态电子邮件。 使用Thymeleaf,您可以轻松编写文本和HTML电子邮件。 要了解有关Thymeleaf的更多信息并下载最新...

    开源框架 Spring Gossip

    org.springframework.mail.javamail.JavaMailSenderImpl。 简单邮件 HTML 邮件 内嵌图片或附档 排程 Spring则对 java.util.Timer提供了抽象封装,让您可以善用Spring的容器管理功能,而Spring对...

    使用Spring的JAVA Mail支持简化邮件发送功能

    主要为大家详细介绍了使用Spring的JAVA Mail支持简化邮件发送功能,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

    Spring发EMail的很好学习实例

    spring 对mail的支持是org.springframework.mail.MailSender接口来定义的,其中的 org.springframework.mail.javamail.JavamailSenderImpl这个实现类提供了对javamail的支持,下面简单介绍其用法,首先看下不用注入...

    SpringMailTest.zip

    Spring 提供了一个发送电子邮件的...它包括了发送电子邮件的主要接口MailSender(实现类为org.springframework.mail.javamail.JavaMailSenderImpl,下面会用到改实现类)和封装了简单邮件属性的值对象SimpleMailMessage.

    mail + spring (maven)

    用maven搭建项目,实现java邮件发送功能,用spring做对象管理和配置管理; maven可以package,install等等;携带所有jar包

    JavaMail 完全攻略(包括可能会出现的问题+源码)

    源码一份,还有你可能遇到的问题 (1)java.lang.NoClassDefFoundError: com/sun/mail/util/LineInputStream (2)java.lang....的解决办法,还有对应的两个包:mail.jar和activation.jar 希望能给你帮助

Global site tag (gtag.js) - Google Analytics