java邮件组建

邮件组建,这个在网上已经是一抓一大把,我也看了许多。但是发现其中功能都过于简单,比如,邮件中无法贴照片,邮件无法带附件,定时发送等等问题。而且这个比较常用,个人比较喜欢偷懒,许多都喜欢做成组建一类,便于以后直接使用。所以这里对这些进行了一下简化和汇总,保证使用的简单和功能的全面。下面直接上代码。

这里话我这分了两个类,一个是用于存储邮件的基本信息如用户名,密码,地址,收件人等等MailSenderInfo.java,还有一个用于初始化邮件,发送邮件MailSender.java

首先是MailSenderInfo.java,具体就看类里面的 成员变量,都有注释,不一一列出来,后面就是一般的get和set方法,注意的是,这个类里面包含了邮件的内容等所有信息,如贴图片,加附件,定时发送都在这个类里面进行设置的,详细见下面demo中使用。

package com.util.mail;

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.MessagingException;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMultipart;

public class MailSenderInfo {
	// 发送邮件的服务器的IP和端口
	private String mailServerHost;
	private String mailServerPort = "25";
	// 邮件发送者的地址
	private String fromAddress;
	// 邮件接收者的地址
	private Address toAddresses[] = null;
	// 邮件抄送者地址
	private Address ccAddresses[] = null;
	// 登陆邮件发送服务器的用户名和密码
	private String userName;
	private String password;
	// 是否需要身份验证
	private boolean validate = false;
	// 邮件主题
	private String subject;
	//
	private MimeMultipart mailBody = new MimeMultipart();
	// 邮件的文本内容
	private String content;
	// 邮件发送时间
	private Date senderTime = null;

	//添加附件
	public boolean addAttachPart(String fileUrl)
	{
		File file=new File(fileUrl);
		if(!file.exists())
			return false;
		MimeBodyPart attchBodyPart=new MimeBodyPart();
		FileDataSource fds=new FileDataSource(fileUrl);
		//是JAF中的一个类,当MimeBodyPart生成具体的MIME消息时,就会调用DataHandler对象对数据进行处理,获取所需的数据信息
		try {
			attchBodyPart.setDataHandler(new DataHandler(fds));
			attchBodyPart.setFileName(fds.getName());
			mailBody.addBodyPart(attchBodyPart);
		} catch (MessagingException e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	public boolean addConent(String content)
	{
		MimeMultipart contentmultipart=new MimeMultipart("related");
		MimeBodyPart htmlBodyPart=new MimeBodyPart(); 
		try {
			htmlBodyPart.setContent(content, "text/html; charset=utf-8");
			mailBody.addBodyPart(htmlBodyPart);
		} catch (MessagingException e) {
			e.printStackTrace();
			return false;
		} 
		return true;
	}
	
	//添加文本和图片
	public boolean addConentAndPicture(String picUri)
	{
		File file=new File(picUri);
		if(!file.exists())
			return false;
		String name=picUri.split("/")[picUri.split("/").length-1];
		MimeBodyPart htmlBodyPart=new MimeBodyPart(); 
		try {
			htmlBodyPart.setContent("<img src='cid:"+name+"' />", "text/html; charset=utf-8");
			mailBody.addBodyPart(htmlBodyPart);
			MimeBodyPart gifBodyPart=new MimeBodyPart();
			FileDataSource fds=new FileDataSource(picUri);
			gifBodyPart.setDataHandler(new DataHandler(fds));
			gifBodyPart.setContentID(name);
			mailBody.addBodyPart(gifBodyPart);
		} catch (MessagingException e) {
			e.printStackTrace();
			return false;
		} 
		return true;
	}

	//获取邮件body
	public MimeMultipart getMailBody()
	{
		return mailBody;
	}
	/**
	 * 获得邮件会话属性
	 */
	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 boolean isValidate() {
		return validate;
	}

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

	public String getFromAddress() {
		return fromAddress;
	}

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

	public String getPassword() {
		return password;
	}

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

	public Address[] getToAddress() {
		return toAddresses;
	}

	public void setToAddress(String toAddress) {
		this.toAddresses = new Address[1];
		try {
			this.toAddresses[0] = new InternetAddress(toAddress);
		} catch (AddressException e) {
			e.printStackTrace();
		}
	}

	public void setToAddress(String toAddresses[]) {
		this.toAddresses = new Address[toAddresses.length];
		for (int i = 0; i < toAddresses.length; i++)
			try {
				this.toAddresses[i] = new InternetAddress(toAddresses[i]);
			} catch (AddressException e) {
				e.printStackTrace();
			}
	}

	public Address[] getCcAddress() {
		return ccAddresses;
	}

	public void setCcAddress(String ccAddress) {
		this.ccAddresses = new Address[1];
		try {
			this.ccAddresses[0] = new InternetAddress(ccAddress);
		} catch (AddressException e) {
			e.printStackTrace();
		}
	}

	public void setCcAddress(String ccAddresses[]) {
		this.ccAddresses = new Address[ccAddresses.length];
		for (int i = 0; i < ccAddresses.length; i++)
			try {
				this.ccAddresses[i] = new InternetAddress(ccAddresses[i]);
			} catch (AddressException e) {
				e.printStackTrace();
			}
	}

	public String getUserName() {
		return userName;
	}

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

	public String getSubject() {
		return subject;
	}

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

	public String getContent() {
		return content;
	}

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

	public Date getSenderTime() {
		return senderTime;
	}

	public void setSenderTime(Date senderTime) {
		this.senderTime = senderTime;
	}
}

然后是MailSender.java 文件,用于初始化邮件,和邮件发送

package com.util.mail;

import java.util.Date;
import java.util.Properties;
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;

public class MailSender {
	/**
	 * 邮件发送初始化
	 */

	public static MimeMessage SendMailIni(MailSenderInfo mailInfo) {
		// 判断是否需要身份认证
		MyAuthenticator authenticator = null;
		Properties pro = mailInfo.getProperties();
		// 如果需要身份认证,则创建一个密码验证器
		if (mailInfo.isValidate())
			authenticator = new MyAuthenticator(mailInfo.getUserName(),mailInfo.getPassword());
		// 根据邮件会话属性和密码验证器构造一个发送邮件的session
		Session sendMailSession = Session
				.getDefaultInstance(pro, authenticator);
		// 根据session创建一个邮件消息
		MimeMessage mailMessage = new MimeMessage(sendMailSession);
		// 创建邮件发送者地址
		Address from;
		try {
			from = new InternetAddress(mailInfo.getFromAddress());

			// 设置邮件消息的发送者
			mailMessage.setFrom(from);
			// Message.RecipientType.TO属性表示接收者的类型为TO
			mailMessage.setRecipients(Message.RecipientType.TO,
					mailInfo.getToAddress());
			// 创建邮件的抄送者地址,并设置到邮件消息中
			if (mailInfo.getCcAddress() != null)
				mailMessage.setRecipients(Message.RecipientType.CC,
						mailInfo.getCcAddress());
			// 设置邮件消息的主题
			mailMessage.setSubject(mailInfo.getSubject());
			// 设置邮件消息发送的时间
			mailMessage.setSentDate(null == mailInfo.getSenderTime() ? new Date(): mailInfo.getSenderTime());
		} catch (AddressException e) {
			e.printStackTrace();
			return null;
		} catch (MessagingException e) {
			e.printStackTrace();
			return null;
		}
		return mailMessage;
	}

	/**
	 * 以HTML格式发送邮件
	 * 
	 * @param mailInfo
	 *            待发送的邮件信息
	 */
	public static boolean sendHtmlMail(MailSenderInfo mailInfo) {
		try {
			MimeMessage msMessage = SendMailIni(mailInfo);
			// MiniMultipart类是一个容器类,包含MimeBodyPart类型的对象
			Multipart mainPart = new MimeMultipart();
			// 创建一个包含HTML内容的MimeBodyPart
			BodyPart html = new MimeBodyPart();
			// 设置HTML内容
			html.setContent(mailInfo.getContent(), "text/html; charset=utf-8");
			mainPart.addBodyPart(html);
			// 将MiniMultipart对象设置为邮件内容
			msMessage.setContent(mainPart);
			// 以文本发送
			// mailMessage.setText(mailContent);
			// 发送邮件
			Transport.send(msMessage);
			return true;
		} catch (MessagingException ex) {
			ex.printStackTrace();
			return false;
		}
	}

	/**
	 * 以HTML格式发送邮件
	 * 
	 * @param mailInfo
	 *            待发送的邮件信息
	 */
	public static boolean sendMail(MailSenderInfo mailInfo) {
		try {
			MimeMessage msMessage = SendMailIni(mailInfo);
			msMessage.setContent(mailInfo.getMailBody());
			// 发送邮件
			Transport.send(msMessage);
			return true;
		} catch (MessagingException ex) {
			ex.printStackTrace();
			return false;
		}
	}
}

下面就是测试的demo

package com.util.mail;

public class Test {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		MailSenderInfo mailInfo = new MailSenderInfo();
		mailInfo.setMailServerHost("smtp.sina.cn");
		mailInfo.setMailServerPort("25");
		mailInfo.setValidate(true);
		mailInfo.setUserName("18795900290@sina.cn");
		mailInfo.setPassword("123456zcw!");
		mailInfo.setFromAddress("18795900290@sina.cn");
		mailInfo.setToAddress("1171793579@qq.com");
		mailInfo.setSubject("测试");//设置邮件标题
		mailInfo.addConent("<br><input type='text' value='test'><br><div style='background-color:red'>");//增加邮件内容
		mailInfo.addConentAndPicture("F://MailLogo.jpg");//增加图片
		mailInfo.addAttachPart("F://test.rar");//添加附件
		MailSender sender=new MailSender();
		System.out.println(sender.sendMail(mailInfo));
	}

}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值