javamail发送文本邮件、HTML邮件及带附件邮件

今天项目有个需求需要定时发送邮件,正好java有javamail,故将代码贴下如下,非纯原创,又代码借鉴:

当然先得下载javamail的jar包了http://www.oracle.com/technetwork/java/javasebusiness/downloads/java-archive-downloads-eeplat-419426.html,我下载的是javamail1.4.5.jar 

贴上我的代码:

    MailInfo类 主要是邮箱相关的登录信息,如邮件服务器地址、端口,账号、密码,邮件收件人、主题、内容等

import java.util.Properties;


public class MailInfo {
	
	private String mailServerHost;// 发送邮件的服务器ip
	private String mailServerPort;// 发送邮件的服务器端口
	private String fromAddress;// 发送者的邮件地址
	private String toAddress;// 邮件接收者地址
	private String username;// 登录邮件发送服务器的用户名
	private String password;// 登录邮件发送服务器的密码
	private boolean validate = false;// 是否需要身份验证
	private String subject;// 邮件主题
	private String content;// 邮件内容
	private String[] attachFileNames;// 附件名称
	
	public Properties getProperties() {
		Properties p = new Properties();
		p.put("mail.smtp.host", this.mailServerHost);
		p.put("mail.smtp.port", this.mailServerPort);
		p.put("mail.smtp.auth", validate ? "true" : "false");
		return p;
	}

	public String getMailServerHost() {
		return mailServerHost;
	}

	public void setMailServerHost(String mailServerHost) {
		this.mailServerHost = mailServerHost;
	}

	public String getMailServerPort() {
		return mailServerPort;
	}

	public void setMailServerPort(String mailServerPort) {
		this.mailServerPort = mailServerPort;
	}

	public String getFromAddress() {
		return fromAddress;
	}

	public void setFromAddress(String fromAddress) {
		this.fromAddress = fromAddress;
	}

	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[] getAttachFileNames() {
		return attachFileNames;
	}

	public void setAttachFileNames(String[] attachFileNames) {
		this.attachFileNames = attachFileNames;
	}

}
 

   MyAuthenticator类,主要是在邮件服务器需要权限认证的时候用

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

public class MyAuthenticator extends Authenticator {
	private String username = null;
	private String password = null;

	public MyAuthenticator() {
	};

	public MyAuthenticator(String username, String password) {
		this.username = username;
		this.password = password;
	}

	protected PasswordAuthentication getPasswordAuthentication() {
		return new PasswordAuthentication(username, password);
	}

}
  

  SimpleMail类,真正发送邮件的功能在这

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

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

/**
 * 简单邮件发送器
 */
public class SimpleMail {

	/**
	 * 以文本格式发送邮件
	 * @param mailInfo待发送的邮件的信息 
	 * @return
	 */
	public static boolean sendTextMail(MailInfo mailInfo) {
		
		//判断是否需要身份认证
		MyAuthenticator authenticator = null;
		Properties properties = mailInfo.getProperties();
		if (mailInfo.isValidate()) {
			//如果需要身份认证,则创建一个密码验证器
			authenticator = new MyAuthenticator(mailInfo.getUsername(), mailInfo.getPassword());
		}
		
		//根据邮件会话属性和密码验证器构造一个发送邮件的session
		Session sendMailSession = Session.getDefaultInstance(properties, authenticator);
		try {
			Message mailMessage = new MimeMessage(sendMailSession);//根据session创建一个邮件消息 
			Address from = new InternetAddress(mailInfo.getFromAddress());//创建邮件发送者地址
			mailMessage.setFrom(from);//设置邮件消息的发送者
			Address to = new InternetAddress(mailInfo.getToAddress());//创建邮件的接收者地址
			mailMessage.setRecipient(Message.RecipientType.TO, to);//设置邮件消息的接收者
			mailMessage.setSubject(mailInfo.getSubject());//设置邮件消息的主题
			mailMessage.setSentDate(new Date());//设置邮件消息发送的时间
			//mailMessage.setText(mailInfo.getContent());//设置邮件消息的主要内容
			
			//MimeMultipart类是一个容器类,包含MimeBodyPart类型的对象
			Multipart mainPart = new MimeMultipart();
			MimeBodyPart messageBodyPart = new MimeBodyPart();//创建一个包含附件内容的MimeBodyPart
			//设置HTML内容
			messageBodyPart.setContent(mailInfo.getContent(),"text/html; charset=utf-8");
			mainPart.addBodyPart(messageBodyPart);

			//存在附件
			String[] filePaths = mailInfo.getAttachFileNames();
			if (filePaths != null && filePaths.length > 0) {
				for(String filePath:filePaths){
					messageBodyPart = new MimeBodyPart();
					File file = new File(filePath); 
					if(file.exists()){//附件存在磁盘中
						FileDataSource fds = new FileDataSource(file);//得到数据源
						messageBodyPart.setDataHandler(new DataHandler(fds));//得到附件本身并至入BodyPart
						messageBodyPart.setFileName(file.getName());//得到文件名同样至入BodyPart
						mainPart.addBodyPart(messageBodyPart);
					}
				}
			}
			
			//将MimeMultipart对象设置为邮件内容   
			mailMessage.setContent(mainPart);
			Transport.send(mailMessage);//发送邮件
			return true;
		} catch (Exception e) {
			e.printStackTrace();  
		}
		return false;
	}
	
	
	/**
	 * 以HTML格式发送邮件 
	 * @param mailInfo 待发送的邮件信息
	 * @return
	 */
	public static boolean sendHtmlMail(MailInfo mailInfo) {
		
		//判断是否需要身份认证
		MyAuthenticator authenticator = null;
		Properties properties = mailInfo.getProperties();
		if (mailInfo.isValidate()) {
			// 如果需要身份认证,则创建一个密码验证器
			authenticator = new MyAuthenticator(mailInfo.getUsername(), mailInfo.getPassword());
		}

		// 根据邮件会话属性和密码验证器构造一个发送邮件的session
		Session sendMailSession = Session.getDefaultInstance(properties, authenticator);
		try{
			Message mailMessage = new MimeMessage(sendMailSession);//根据session创建一个邮件消息 
			Address from = new InternetAddress(mailInfo.getFromAddress());//创建邮件发送者地址
			mailMessage.setFrom(from);//设置邮件消息的发送者
			Address to = new InternetAddress(mailInfo.getToAddress());//创建邮件的接收者地址
			mailMessage.setRecipient(Message.RecipientType.TO, to);//设置邮件消息的接收者
			mailMessage.setSubject(mailInfo.getSubject());//设置邮件消息的主题
			mailMessage.setSentDate(new Date());//设置邮件消息发送的时间
			
			//MimeMultipart类是一个容器类,包含MimeBodyPart类型的对象
			Multipart mainPart = new MimeMultipart();
			MimeBodyPart messageBodyPart = new MimeBodyPart();//创建一个包含HTML内容的MimeBodyPart
			//设置HTML内容
			messageBodyPart.setContent(mailInfo.getContent(),"text/html; charset=utf-8");
			mainPart.addBodyPart(messageBodyPart);
			
			//存在附件
			String[] filePaths = mailInfo.getAttachFileNames();
			if (filePaths != null && filePaths.length > 0) {
				for(String filePath:filePaths){
					messageBodyPart = new MimeBodyPart();
					File file = new File(filePath); 
					if(file.exists()){//附件存在磁盘中
						FileDataSource fds = new FileDataSource(file);//得到数据源
						messageBodyPart.setDataHandler(new DataHandler(fds));//得到附件本身并至入BodyPart
						messageBodyPart.setFileName(file.getName());//得到文件名同样至入BodyPart
						mainPart.addBodyPart(messageBodyPart);
					}
				}
			}
			
			//将MimeMultipart对象设置为邮件内容   
			mailMessage.setContent(mainPart);
			Transport.send(mailMessage);//发送邮件
			return true;
		}catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

}

上面就是我的javamai发送邮件的功能代码,下面贴上我的测试代码:

public class Test {
	public static void main(String[] args) {
		MailInfo mailInfo = new MailInfo();
		mailInfo.setMailServerHost("smtp.126.com");
		mailInfo.setMailServerPort("25");
		mailInfo.setValidate(true);
		mailInfo.setUsername("[email protected]");
		mailInfo.setPassword("******");// 您的邮箱密码
		mailInfo.setFromAddress("[email protected]");
		mailInfo.setToAddress("[email protected]");
		mailInfo.setSubject("设置邮箱标题");
		mailInfo.setContent("设置邮箱内容");
		String[] attachFileNames={"D:/demo.xml","d:/demo.png"};
		mailInfo.setAttachFileNames(attachFileNames);//附件
		
		// 这个类主要来发送邮件
		SimpleMail.sendTextMail(mailInfo);// 发送文体格式
		StringBuffer demo = new StringBuffer();
		demo.append("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">")
		.append("<html>")
		.append("<head>")
		.append("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">")
		.append("<title>测试邮件</title>")
		.append("<style type=\"text/css\">")
		.append(".test{font-family:\"Microsoft Yahei\";font-size: 18px;color: red;}")
		.append("</style>")
		.append("</head>")
		.append("<body>")
		.append("<span class=\"test\">大家好,这里是测试Demo</span>")
		.append("</body>")
		.append("</html>");
		mailInfo.setContent(demo.toString());
		SimpleMail.sendHtmlMail(mailInfo);// 发送html格式
	}
}
   

猜你喜欢

转载自ducaijun.iteye.com/blog/1664404