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

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 是一个基于 Java 的库,它为使用 JavaMail API 发送电子邮件提供了便捷的抽象层。这个框架使得在 Spring 应用程序中集成邮件服务变得简单。本文将深入探讨 SpringMail 的核心概念、配置以及如何在实际...

    spring mail通过代理发送邮件

    要使用Spring Mail,你需要在项目中引入`spring-context-support`依赖,这个依赖包含了对邮件服务的支持。接着,你需要配置一个`JavaMailSender`实例,该实例是Spring Mail的核心接口,负责邮件的发送工作。配置通常...

    spring mail

    Spring Mail 提供了一种优雅的方式来配置和使用JavaMail API,而无需直接处理复杂的JavaMail API细节。下面将详细阐述Spring Mail的核心概念、配置、使用方法以及常见应用场景。 一、核心概念 1. JavaMail API:...

    spring mail的使用

    &lt;bean id="javaMailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl"&gt; ${mail.smtp.host}" /&gt; ${mail.smtp.port}" /&gt; ${mail.from}" /&gt; ${mail.password}" /&gt; &lt;prop key="mail....

    使用springMail发送带附件的email

    SpringMail是一个在Java应用中发送电子邮件的库,它利用了JavaMail API的简便性和灵活性。在本项目中,我们将深入探讨如何使用SpringMail发送带有附件的电子邮件。首先,我们需要了解几个核心概念: 1. **JavaMail ...

    利用 spring mail 通过 gmail(SSL) 发邮件

    Spring Mail是一个Java库,它简化了通过JavaMail API发送电子邮件的过程。本教程将详细讲解如何利用Spring Mail通过Gmail的SSL(安全套接层)协议来发送邮件。 首先,我们需要在项目中引入Spring Mail的依赖。如果...

    Spring mail发送邮件实例

    &lt;bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl"&gt; &lt;value&gt;smtp.163.com&lt;/value&gt; &lt;prop key="mail.smtp.auth"&gt;true &lt;prop key="mail.smtp.timeout"&gt;25000 ...

    spring mail 的发送

    在`springmail2`这个示例项目中,可能包含了一个简单的Spring Boot应用,演示了如何使用Spring Mail发送邮件。这个示例可能包括一个`Main`类,启动Spring Boot应用,并调用`MailService`发送一封测试邮件。代码可能...

    SpringMail发邮件

    SpringMail的核心依赖是JavaMail API,这是一个广泛使用的Java邮件处理库。JavaMail提供了与各种邮件服务器交互的接口,如SMTP(简单邮件传输协议)、POP3(邮局协议)和IMAP(因特网消息访问协议)。SpringMail则将...

    spring + mail + 发送邮件完整 demo (含注释)

    Spring框架提供了集成JavaMail API的能力,使得发送邮件变得简单易行。本教程将围绕"Spring + Mail"的组合,结合Freemarker模板引擎,提供一个完整的发送邮件的Demo。 首先,我们需要在项目中添加相关的依赖。...

    Spring实现JavaMail邮件发送功能

    其中,Spring的JavaMail支持使得开发者能够轻松地实现邮件发送功能。在本篇文章中,我们将深入探讨如何利用Spring来实现JavaMail邮件发送,以及在实际应用中需要注意的关键点。 首先,我们需要理解JavaMail API的...

    spring结合javamail开发文档

    #### 二、Spring对JavaMail的支持 Spring框架通过提供一套简洁易用的API来简化JavaMail的使用。主要体现在以下几个方面: 1. **邮件发送支持**: - **SimpleMailMessage**: 用于发送纯文本邮件。 - **...

    javamail+spring

    &lt;bean id="javaMailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl"&gt; &lt;prop key="mail.smtp.auth"&gt;true &lt;prop key="mail.smtp.starttls.enable"&gt;true ``` **发送邮件** ...

    JavaMail实现源代码和jar包

    1. **mail.jar**:这是一个核心的 JavaMail JAR 文件,包含了 JavaMail API 的所有类和接口,如 `javax.mail` 和 `javax.mail.internet` 包。这些类提供了创建、发送、读取邮件以及处理附件等功能。例如,`Message` ...

    Spring整合JavaMail发送qq邮件

    &lt;bean id="javaMailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl"&gt; &lt;prop key="mail.smtp.auth"&gt;true &lt;prop key="mail.smtp.starttls.enable"&gt;true &lt;prop key="mail....

    Spring mail 发送邮件

    &lt;bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl"&gt; &lt;prop key="mail.smtp.auth"&gt;true &lt;prop key="mail.smtp.starttls.enable"&gt;true ``` 配置完成后,...

    SpringMail

    SpringMail 提供了一种方便的方式来配置和使用 JavaMail API,避免了直接与复杂的 JavaMail API 接触,降低了开发难度。 ### **一、SpringMail 的核心概念** 1. **JavaMail API**: SpringMail 基于 JavaMail API,...

    Spring mail 使用多个账号发送带有附件的HTML邮件

    Spring Mail支持发送HTML格式的邮件,这在创建有样式的邮件时非常有用。我们可以通过设置`MimeMessageHelper`的`isHtml`属性为`true`来指定邮件内容是HTML格式,然后使用`addAltBody`方法添加纯文本版本,以便不...

Global site tag (gtag.js) - Google Analytics