JavaMail

1、JavaMail简介

JavaMail,顾名思义,提供给开发者处理电子邮件相关的编程接口。它是Sun发布的用来处理email的API。它可以方便地执行一些常用的邮件传输。

2、JavaMail例子

下面将使用Spring整合JavaMail来发送邮件,可以发送文本邮件,HTML邮件,附件,抄送人。

2.1 发送邮件的接口类

package com.javamail;

/**
 * 邮件服务接口
 */
public interface MailSendService {

	/**
	 * 发送纯文本的邮件.
	 */
	public void sendText(String subject,String content,String[] mailto) throws Exception;
	
	/**
	 * 发送HTML格式邮件
	 */
	public void sendHtml(String subject,String content,String[] mailto) throws Exception;
	
	/**
	 * 发送带附件的HTML邮件
	 */
	public void sendHtmlWithAttachment(String subject, String content,String[] mailto,String[] filepaths) throws Exception;
	
	/**
	 * 发送带附件的HTML邮件,区分收件人和抄送
	 */
	public void sendHtmlWithAttachmentAndCopyTo(String subject, String content,String[] mailto,String copyTo[],String[] filepaths) throws Exception;
}

2.2 接口实现类

package com.javamail;

import java.io.File;

import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;

/**
 * 邮件服务实现类 
 */
public class MailSendServiceImpl implements MailSendService{
	
	private static final Logger logger = LoggerFactory.getLogger(MailSendServiceImpl.class);
	
	private static final String err = "系统发送邮件出现异常!!";
	
	private String formMail; 
	
	private JavaMailSender mailSender;
	
	public void setFormMail(String formMail) {
		this.formMail = formMail;
	}

	public void setMailSender(JavaMailSender mailSender) {
		this.mailSender = mailSender;
	}

	public void sendText(String subject, String content, String[] mailto)
			throws Exception {
		SimpleMailMessage msg = new SimpleMailMessage();
		msg.setFrom(formMail);
		msg.setTo(mailto);
		msg.setSubject(subject);
		msg.setText(content);
		try {
			mailSender.send(msg);
		} catch (Exception e) {
			logger.error(err,e);
			throw new Exception(err,e);
		}
	}
	
	public void sendHtml(String subject, String content, String[] mailto)
			throws Exception {
		try{
			MimeMessage mimeMessage = mailSender.createMimeMessage();
			MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage);
			messageHelper.setTo(mailto);
			messageHelper.setBcc(formMail);
			messageHelper.setFrom(formMail,"test");
			messageHelper.setSubject(subject);
			messageHelper.setText(content, true);
			mailSender.send(mimeMessage);
		} catch (Exception e) {
			logger.error(err,e);
			throw new Exception(err,e);
		}
	}

	public void sendHtmlWithAttachment(String subject, String content,
			String[] mailto, String[] filepaths) throws Exception {
		try{
			MimeMessage mimeMessage = mailSender.createMimeMessage();
			MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage,true);
			messageHelper.setTo(mailto);
			messageHelper.setBcc(formMail);
			messageHelper.setFrom(formMail,"brushli");
			messageHelper.setSubject(subject);
			messageHelper.setText(content, true);
			
			if(filepaths != null){
				for(String filepath : filepaths){
					FileSystemResource file = new FileSystemResource(new File(filepath));
					messageHelper.addAttachment(MimeUtility.encodeWord(file.getFilename(), "UTF-8",null), file);
				}
			}
			
			mailSender.send(mimeMessage);
		} catch (Exception e) {
			logger.error(err,e);
			throw new Exception(err,e);
		}
	}

	public void sendHtmlWithAttachmentAndCopyTo(String subject,
			String content, String[] mailto, String[] copyTo, String[] filepaths)
			throws Exception {
		try {
			MimeMessage mimeMessage = mailSender.createMimeMessage();
			MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true);
			messageHelper.setTo(mailto);
			messageHelper.setBcc(formMail);
			messageHelper.setFrom(formMail, "brushli");
			messageHelper.setCc(copyTo);
			messageHelper.setSubject(subject);
			messageHelper.setText(content, true);

			if (filepaths != null) {
				for (String filepath : filepaths) {
					FileSystemResource file = new FileSystemResource(new File(filepath));
					messageHelper.addAttachment(MimeUtility.encodeWord(file.getFilename(), "UTF-8", null), file);
				}
			}

			mailSender.send(mimeMessage);
		} catch (Exception e) {
			logger.error(err, e);
			throw new Exception(err, e);
		}
	}
	
}

2.3 Spring配置文件applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>  
<beans xmlns="http://www.springframework.org/schema/beans"  
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    xmlns:context="http://www.springframework.org/schema/context"  
    xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd    
           http://www.springframework.org/schema/context     
            http://www.springframework.org/schema/context/spring-context-3.0.xsd">
       
    	<!-- 邮件发送器 -->
	<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
       <property name="host" value="smtp.163.com" />
       <property name="username" value="XXX@163.com" />
       <property name="password" value="XXX" />
       <property name="port" value="25" />
	   <property name="defaultEncoding" value="UTF-8" />
	   <property name="javaMailProperties">
	       <props>
	           	<prop key="mail.smtp.auth">true</prop>
	           	<!-- 使用gmail smtp server的必须参数 -->
				<prop key="mail.smtp.starttls.enable">true</prop>
			</props>
		</property>
	</bean>
	
	<bean id="mailSendService" class="com.javamail.MailSendServiceImpl">
		<property name="mailSender" ref="mailSender"/>
		<property name="formMail" value="XXX@163.com"/>
	</bean>
</beans>

2.4 测试类

package com.javamail;


import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {
	private static Logger logger = LoggerFactory.getLogger(Test.class);
	
	public static void main(String[] args) {
		ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
		MailSendService service = (MailSendService)context.getBean("mailSendService");
		try {
			String[] mailTo = new String[]{"XXX@qq.com"};//收件人
			String[] copyTo = new String[]{<a target=_blank href="mailto:XXX@qq.com">XXX@qq.com</a>};//抄送人
			String subject = "subject";//主题
			String content = "content";//内容
			String htmlContent = "<html><head><title>test html email</title></head><body>test html email</body></html>";
			String[] attachments = new String[]{"E:\\workspace\\javaMail\\src\\com\\images\\iphone5S.jpg"};//附件
			logger.info("begin to send email");
			Map<String, String> images = new HashMap<String, String>();//图片
			images.put("iphone5S.jpg", "E:\\workspace\\javaMail\\src\\com\\images\\iphone5S.jpg");
			images.put("thinkpad sl400.jpg", "E:\\workspace\\javaMail\\src\\com\\images\\thinkpad sl400.jpg");
			service.sendText(subject, content, mailTo);
			service.sendHtml(subject, htmlContent, mailTo);
			service.sendHtmlWithAttachment(subject, htmlContent, mailTo, attachments);
			service.sendHtmlWithAttachmentAndCopyTo(subject, htmlContent, mailTo, copyTo, attachments);
			logger.info("send email success");
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("send email error! " + e.getMessage());
		}
	}
}

2.5 程序运行结果

2014-8-4 21:43:34 org.springframework.context.support.AbstractApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@1cafa9e: startup date [Mon Aug 04 21:43:34 CST 2014]; root of context hierarchy
2014-8-4 21:43:34 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [applicationContext.xml]
2014-8-4 21:43:34 org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
信息: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@166aa18: defining beans [mailSender,mailSendService]; root of factory hierarchy
562 [main] INFO com.javamail.Test - begin to send email
29406 [main] INFO com.javamail.Test - send email success

2.6 程序下载地址

http://download.youkuaiyun.com/detail/brushli/7714667

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值