利用Javamail发送邮件(支持附件)

准备Javamail包,下载地址 http://www.oracle.com/technetwork/java/index-138643.html,具体实现如下:
package org.asheng.util;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;

import org.asheng.model.Email;

/**
 * 邮件发送器,支持附件
 * @author Harrison Wang
 */
public class MailSender {

	/* 定义邮件身份验证器 */
	private EmailAuthenticator authenticator;

	/**
	 * 以文本方式发送邮件
	 * @param email 待发送邮件的信息
	 * @return 成功则返回true,反之则返回false
	 */
	public boolean sendTextMail(Email email) {
		// 获取邮件会话属性
		Properties props = email.getProperties();
		// 判断是否需要身份验证,如需身份验证,则创建一个身份验证器
		if (email.isValidate()) {
			authenticator = new EmailAuthenticator(email.getUserName(),
					email.getPassword());
		}
		// 根据邮件会话属性和密码验证器构造一个发送邮件的session
		Session session = Session.getDefaultInstance(props, authenticator);
		// 根据session创建一个邮件消息
		Message message = new MimeMessage(session);
		try {
			// 创建邮件发送者地址
			Address from = new InternetAddress(email.getFormAddress());
			// 设置邮件消息发送者
			message.setFrom(from);
			// 创建邮件的接收者地址,并设置到邮件消息中
			Address to = new InternetAddress(email.getToAddress());
			message.setRecipient(Message.RecipientType.TO, to);
			// 设置邮件消息主题
			message.setSubject(email.getSubject());
			// 设置邮件消息发送的时间
			message.setSentDate(new Date());
			// 设置邮件消息主要内容
			message.setText(email.getContent());
			// 发送邮件
			Transport.send(message);
			return true;
		} catch (AddressException e) {
			e.printStackTrace();
		} catch (MessagingException e) {
			e.printStackTrace();
		}
		return false;
	}
	
	/**
	 * 以HTML方式发送邮件
	 * @param email 待发送邮件的信息
	 * @return 成功则返回true,反之则返回false
	 */
	public boolean sendHtmlMail(Email email) {
		// 获取邮件会话属性
		Properties props = email.getProperties();
		// 判断是否需要身份验证,如需身份验证,则创建一个身份验证器
		if (email.isValidate()) {
			authenticator = new EmailAuthenticator(email.getUserName(),
					email.getPassword());
		}
		// 根据邮件会话属性和密码验证器构造一个发送邮件的session
		Session session = Session.getDefaultInstance(props, authenticator);
		// 根据session创建一个邮件消息
		Message message = new MimeMessage(session);
		try {
			// 创建邮件发送者地址
			Address from = new InternetAddress(email.getFormAddress());
			// 设置邮件消息发送者
			message.setFrom(from);
			// 创建邮件的接收者地址,并设置到邮件消息中
			Address to = new InternetAddress(email.getToAddress());
			message.setRecipient(Message.RecipientType.TO, to);
			// 设置邮件消息主题
			message.setSubject(email.getSubject());
			// 设置邮件消息发送的时间
			message.setSentDate(new Date());
			
			// MimeMultipart类是一个容器类,包含MimeBodyPart类型的对象
			Multipart multipart = new MimeMultipart();
			
			// 创建一个包含HTML内容的MimeBodyPart
			BodyPart html = new MimeBodyPart();
			// 设置HTML内容
			html.setContent(email.getContent(),"text/html; charset=UTF-8");
			// 添加到Multipart容器类中
			multipart.addBodyPart(html);
			
			// 创建一个包含附件的	MimeBodyPart
			BodyPart attachmentInfo = new MimeBodyPart();
			// 得到数据源
			FileDataSource dataSource = new FileDataSource(
					email.getAttachmentName());
			// 得到附件本身并绑定到对象BodyPart中
			attachmentInfo.setDataHandler(new DataHandler(dataSource));
			// 设置附件名称,处理中文文件名
			attachmentInfo.setFileName(MimeUtility.encodeWord(
					dataSource.getName(), "text/html; charset=UTF-8", "UTF-8"));
			// 添加到Multipart容器类中
			multipart.addBodyPart(attachmentInfo);
			
			// 将MimeMultipart对象设置为邮件内容  
			message.setContent(multipart);
			
			// 发送邮件
			Transport.send(message);
			return true;
		} catch (AddressException e) {
			e.printStackTrace();
		} catch (MessagingException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return false;
	}
	
	public static void main(String[] args) {
		MailSender sms = new MailSender();
		Email email = new Email();
		email.setServerHost("smtp.163.com");
		email.setServerPort("25");
		email.setUserName("[email protected]");
		email.setPassword("**********");
		email.setFormAddress("[email protected]");
		email.setToAddress("[email protected]");
		email.setSubject("harrison 你好!");
		email.setContent("<font color='red'>Hello Harrison!</font>");
		email.setAttachmentName("D:/Download/Converter.rar");
//		sms.sendTextMail(email);
		sms.sendHtmlMail(email);
		
	}

}



package org.asheng.model;

import java.io.Serializable;
import java.util.Date;
import java.util.Properties;

/**
 * 邮件基本信息类
 * @author Harrison Wang
 */
public class Email implements Serializable {
	private static final long serialVersionUID = 1L;
	
	// 发送邮件的服务器主机地址
	private String serverHost;
	// 发送邮件的服务器端口
	private String serverPort = "25";
	// 邮件发送者email地址
	private String formAddress;
	// 邮件接收者email地址
	private String toAddress;

	// 登录邮件发送服务器的用户名
	private String userName;
	// 登录邮件发送服务器的密码
	private String password;
	
	// 是否需要身份验证
	private boolean validate = true;

	// 邮件主题
	private String subject;
	// 邮件文本内容
	private String content;
	// 邮件附件的文件名
	private String attachmentName;
	// 邮件发送时间
	private Date sendTime;

	/**
	 * 获取邮件会话属性
	 * @return 返回邮件会话属性
	 */
	public Properties getProperties() {
		Properties props = new Properties();
		props.setProperty("mail.smtp.host", serverHost);
		props.setProperty("mail.smtp.port", serverPort);
		props.setProperty("mail.smtp.auth", validate ? "true" : "false");
		return props;
	}

	public String getServerHost() {
		return serverHost;
	}

	public void setServerHost(String serverHost) {
		this.serverHost = serverHost;
	}

	public String getServerPort() {
		return serverPort;
	}

	public void setServerPort(String serverPort) {
		this.serverPort = serverPort;
	}

	public String getFormAddress() {
		return formAddress;
	}

	public void setFormAddress(String formAddress) {
		this.formAddress = formAddress;
	}

	public String getToAddress() {
		return toAddress;
	}

	public void setToAddress(String toAddress) {
		this.toAddress = toAddress;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public boolean isValidate() {
		return validate;
	}

	public void setValidate(boolean validate) {
		this.validate = validate;
	}

	public String getSubject() {
		return subject;
	}

	public void setSubject(String subject) {
		this.subject = subject;
	}

	public String getContent() {
		return content;
	}

	public void setContent(String content) {
		this.content = content;
	}

	public String getAttachmentName() {
		return attachmentName;
	}

	public void setAttachmentName(String attachmentName) {
		this.attachmentName = attachmentName;
	}

	public Date getSendTime() {
		return sendTime;
	}

	public void setSendTime(Date sendTime) {
		this.sendTime = sendTime;
	}
	
}



package org.asheng.util;

import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;

public class EmailAuthenticator extends Authenticator {

	private String userName;
	private String password;
	
	public EmailAuthenticator() {
	}
	
	public EmailAuthenticator(String userName, String password) {
		this.userName = userName;
		this.password = password;
	}

	@Override
	protected PasswordAuthentication getPasswordAuthentication() {
		return new PasswordAuthentication(userName, password);
	}
	
}

你可能感兴趣的:(html,oracle,qq)