分享一个JavaMail发邮件的类,可以内嵌图片

package wfc.service.util;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.Message.RecipientType;
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.htmlparser.Node;
import org.htmlparser.Parser;
import org.htmlparser.Tag;
import org.htmlparser.filters.HasAttributeFilter;
import org.htmlparser.filters.TagNameFilter;
import org.htmlparser.tags.ImageTag;
import org.htmlparser.util.NodeIterator;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;

import wfc.service.log.Log;

/**
 * 邮件处理<br>
 * 
 * <p>
 * <b>使用示例</b>
 * <p style="margin-left:35px">
 * <code><b>
 * <br>MailSender mailSender = new MailSender("mail-svr", "user", "pwd");
 * <br>mailSender.setFromAddress("yuyue@wondersgroup.com");
 * <br>mailSender.setSubject("测试邮件");
 * <br>mailSender.addTOAddress("chenlin@wondersgroup.com");
 * <br>mailSender.addCCAddress("yuyue@wondersgroup.com");
 * <br>mailSender.addURLAttachment("http://www.sina.com.cn");
 * <br>mailSender.addFileAttachment("c:\\autoexec.bat");
 * <br>mailSender.send();
 * </b></code>
 * 
 */

public class MailSender {

	/** 邮件优先级, 最高级 */
	public static String PRIORITY_HIGHEST = "1";

	/** 邮件优先级, 高级 */
	public static String PRIORITY_HIGH = "2";

	/** 邮件优先级, 普通级 */
	public static String PRIORITY_NORMAL = "3";

	/** 邮件优先级, 低级 */
	public static String PRIORITY_LOW = "4";

	/** 邮件优先级, 最低级 */
	public static String PRIORITY_LOWEST = "5";

	/** 邮件发送对象 */
	private MimeMessage mimeMessage;

	/** 邮件相关信息 - 邮件正文(复合结构) */
	private MimeMultipart mimeMultipart = new MimeMultipart("related");

	/**
	 * 构造函数
	 * 
	 * @param host
	 *            邮件SMTP服务器地址或名称
	 * @param port
	 *            邮件SMTP服务器端口号
	 * @param username
	 *            登录用户
	 * @param password
	 *            用户口令
	 */
	public MailSender(String host, int port, String username, String password)
			throws MessagingException {
		init(host, new Integer(port), username, password);
	}

	/**
	 * 构造函数, 默认SMTP服务器端口为25
	 * 
	 * @param host
	 *            邮件SMTP服务器地址或名称
	 * @param username
	 *            登录用户
	 * @param password
	 *            用户口令
	 */
	public MailSender(String host, String username, String password)
			throws MessagingException {
		init(host, null, username, password);
	}

	/**
	 * 构造函数, 匿名发送需服务器支持
	 * 
	 * @param host
	 *            邮件SMTP服务器地址或名称
	 * @param port
	 *            邮件SMTP服务器端口号
	 */
	public MailSender(String host, int port) throws MessagingException {
		init(host, new Integer(port), null, null);
	}

	/**
	 * 构造函数, 默认SMTP服务器端口为25, 匿名发送需服务器支持
	 * 
	 * @param host
	 *            邮件SMTP服务器地址或名称
	 */
	public MailSender(String host) throws MessagingException {
		init(host, null, null, null);
	}

	private void init(String host, Integer port, String username,
			String password) throws MessagingException {
		Properties properties = System.getProperties();
		properties.put("mail.smtp.host", host);
		if (port != null) {
			properties.put("mail.smtp.port", String.valueOf(port.intValue()));
		}
		Session session;
		if (username != null) {
			properties.put("mail.smtp.auth", "true");
			Authenticator auth = new MailAuthenticator(username, password);
			session = Session.getInstance(properties, auth);
		} else {
			session = Session.getInstance(properties);
		}
		mimeMessage = new MimeMessage(session);
		mimeMessage.setSentDate(new Date());
		mimeMessage.setContent(mimeMultipart);
	}

	/**
	 * 设置邮件发送地址
	 * 
	 * @param address
	 *            邮件发送地址
	 */
	public void setFromAddress(String address) throws MessagingException {
		mimeMessage.setFrom(new InternetAddress(address));
	}

	/**
	 * 设置邮件普通接收方地址
	 * 
	 * @param address
	 *            邮件地址
	 * @throws MessagingException
	 */
	public void addTOAddress(String address) throws MessagingException {
		mimeMessage.addRecipients(RecipientType.TO, address);
	}

	/**
	 * 设置邮件抄送接收方地址
	 * 
	 * @param address
	 *            邮件地址
	 * @throws MessagingException
	 */
	public void addCCAddress(String address) throws MessagingException {
		mimeMessage.addRecipients(RecipientType.CC, address);
	}

	/**
	 * 设置邮件密件抄送接收方地址
	 * 
	 * @param address
	 *            邮件地址
	 * @throws MessagingException
	 */
	public void addBCCAddress(String address) throws MessagingException {
		mimeMessage.addRecipients(RecipientType.BCC, address);
	}

	/**
	 * 设置邮件回复地址
	 * 
	 * @param address
	 *            邮件回复地址
	 */
	public void setReplyAddress(String address) throws MessagingException {
		Address[] addresses = { new InternetAddress(address) };
		mimeMessage.setReplyTo(addresses);
	}

	/**
	 * 设置邮件主题
	 * 
	 * @param subject
	 *            邮件主题
	 */
	public void setSubject(String subject) throws MessagingException {
		mimeMessage.setSubject(subject);
	}

	/**
	 * 设置邮件优先级
	 * 
	 * @param priority
	 *            优先级, 见常量定义
	 * @throws MessagingException
	 */
	public void setPriority(String priority) throws MessagingException {
		mimeMessage.addHeader("X-Priority", priority);
	}

	/**
	 * 设置邮件文本正文
	 * 
	 * @param textBody
	 *            邮件文本正文
	 * @throws MessagingException
	 */
	public void addTextBody(String textBody) throws MessagingException {
		MimeBodyPart mimeBodyPart = new MimeBodyPart();
		mimeBodyPart.setText(textBody, "GBK");
		mimeMultipart.addBodyPart(mimeBodyPart);
	}

	/**
	 * 设置邮件超文本正文
	 * 
	 * @param htmlBody
	 *            邮件超文本正文
	 * @throws MessagingException
	 */
	public void addHtmlBody(String htmlBody) throws MessagingException {
		MimeBodyPart mimeBodyPart = new MimeBodyPart();
		mimeBodyPart.setDataHandler(new DataHandler(htmlBody,
				"text/html;charset=GBK"));
		mimeMultipart.addBodyPart(mimeBodyPart);
	}

	/**
	 * 设置邮件正文外部链接 URL, 信体中将包含链接所指向的内容
	 * 
	 * @param urlAttachment
	 *            邮件正文外部链接 URL
	 * @throws MessagingException
	 * @throws MalformedURLException
	 */
	public void addURLAttachment(String urlAttachment)
			throws MessagingException, MalformedURLException {
		MimeBodyPart mimeBodyPart = new MimeBodyPart();
		mimeBodyPart.setDataHandler(new DataHandler(new URL(urlAttachment)));
		mimeMultipart.addBodyPart(mimeBodyPart);
	}

	/**
	 * 设置邮件正文外部链接 URL, 信体中将包含链接所指向的内容(包括链接所引用的图片文件)
	 * 
	 * @param urlEmbeddedAttachment
	 *            邮件正文外部链接 URL
	 * @throws MessagingException
	 * @throws MalformedURLException
	 * @throws ParserException
	 * @throws IOException
	 */
	public void addURLEmbeddedAttachment(String urlEmbeddedAttachment)
			throws MessagingException, MalformedURLException, ParserException,
			IOException {
		URL url = new URL(urlEmbeddedAttachment);
		URLConnection con = url.openConnection();
		Parser parser = new Parser(con);
		parser.setEncoding("GBK");
		NodeList htmlNodeList = new NodeList();
		NodeList linkNodeList = new NodeList();
		NodeList imageNodeList = new NodeList();
		NodeList backgroundNodeList = new NodeList();
		NodeIterator ni = parser.elements();
		while (ni.hasMoreNodes()) {
			Node node = ni.nextNode();
			node.collectInto(linkNodeList, new TagNameFilter("LINK"));
			node.collectInto(imageNodeList, new TagNameFilter("IMG"));
			node.collectInto(htmlNodeList, new TagNameFilter("HTML"));
			node.collectInto(backgroundNodeList, new HasAttributeFilter(
					"BACKGROUND"));
		}
		for (int i = 0; i < linkNodeList.size(); i++) {
			Tag tag = (Tag) linkNodeList.elementAt(i);
			String linkUrl = tag.getPage().getAbsoluteURL(
					tag.getAttribute("href"));
			tag.setAttribute("href", "cid:LNK" + i);
			MimeBodyPart mimeBodyPart = new MimeBodyPart();
			mimeBodyPart.setDataHandler(new DataHandler(new URL(linkUrl)));
			mimeBodyPart.setHeader("Content-ID", "LNK" + i);
			mimeMultipart.addBodyPart(mimeBodyPart);
		}
		for (int i = 0; i < imageNodeList.size(); i++) {
			ImageTag tag = (ImageTag) imageNodeList.elementAt(i);
			String imageUrl = tag.getImageURL();
			tag.setImageURL("cid:IMG" + i);
			MimeBodyPart mimeBodyPart = new MimeBodyPart();
			mimeBodyPart.setDataHandler(new DataHandler(new URL(imageUrl)));
			mimeBodyPart.setHeader("Content-ID", "IMG" + i);
			mimeMultipart.addBodyPart(mimeBodyPart);
		}
		for (int i = 0; i < backgroundNodeList.size(); i++) {
			Tag tag = (Tag) backgroundNodeList.elementAt(i);
			String imageUrl = tag.getPage().getAbsoluteURL(
					tag.getAttribute("background"));
			tag.setAttribute("background", "cid:BGIMG" + i);
			MimeBodyPart mimeBodyPart = new MimeBodyPart();
			mimeBodyPart.setDataHandler(new DataHandler(new URL(imageUrl)));
			mimeBodyPart.setHeader("Content-ID", "BGIMG" + i);
			mimeMultipart.addBodyPart(mimeBodyPart);
		}
		MimeBodyPart mimeBodyPart = new MimeBodyPart();
		mimeBodyPart.setDataHandler(new DataHandler(htmlNodeList.elementAt(0)
				.toHtml(), "text/html;charset=GBK"));
		mimeMultipart.addBodyPart(mimeBodyPart);
	}

	/**
	 * 设置邮件附件
	 * 
	 * @param fileAttachment
	 *            文件的全路径
	 * @throws MessagingException
	 * @throws UnsupportedEncodingException
	 */
	public void addFileAttachment(String fileAttachment)
			throws MessagingException, UnsupportedEncodingException {
		File file = new File(fileAttachment);
		if (!file.exists() || file.isDirectory()) {
			return;
		}
		MimeBodyPart mimeBodyPart = new MimeBodyPart();
		mimeBodyPart.setDataHandler(new DataHandler(new FileDataSource(
				fileAttachment)));
		// modified by zord @ 2003/6/16 to support Chinese File Name
		mimeBodyPart.setFileName(MimeUtility.encodeText(file.getName()));
		mimeMultipart.addBodyPart(mimeBodyPart);
	}

	/**
	 * 邮件发送(一次发送多个地址, 优点速度快, 但是有非法邮件地址时将中断发送操作)
	 * 
	 * @throws MessagingException
	 */
	public void sendBatch() throws MessagingException {
		Transport.send(mimeMessage);
		Address[] addresses = mimeMessage.getAllRecipients();
		for (int i = 0; i < addresses.length; i++) {
			Log.debug(addresses[i] + " 发送成功");
		}
	}

	/**
	 * 邮件发送(一个地址一个地址地发送, 优点是有非法邮件地址时不会中断发送操作, 缺点速度慢)
	 * 
	 * @throws MessagingException
	 */
	public void send() throws MessagingException {
		Address[] addresses = mimeMessage.getAllRecipients();
		for (int i = 0; i < addresses.length; i++) {
			try {
				Transport.send(mimeMessage, new Address[] { addresses[i] });
				Log.debug(addresses[i] + " 发送成功");
			} catch (MessagingException e) {
				Log.error(e);
				Log.debug(addresses[i] + " 发送失败");
			}
		}
	}

	private static class MailAuthenticator extends Authenticator {
		private String user;
		private String pass;

		public MailAuthenticator(String user, String pass) {
			this.user = user;
			this.pass = pass;
		}

		protected PasswordAuthentication getPasswordAuthentication() {
			return new PasswordAuthentication(user, pass);
		}
	}

}


 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我可以回答这个问题。以下是一个简单的JavaMail工具的示例代码,包括注释: ```java import java.util.Properties; import javax.mail.*; import javax.mail.internet.*; public class JavaMailUtil { // 发送邮件的方法 public static void sendEmail(String recipient, String subject, String body) throws MessagingException { // 配置邮件服务器 Properties properties = new Properties(); properties.put("mail.smtp.host", "smtp.gmail.com"); // 邮件服务器地址 properties.put("mail.smtp.port", "587"); // 邮件服务器端口 properties.put("mail.smtp.auth", "true"); // 需要认证 // 创建Session对象 Session session = Session.getInstance(properties, new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("[email protected]", "your_password"); } }); // 创建邮件对象 Message message = new MimeMessage(session); message.setFrom(new InternetAddress("[email protected]")); // 发件人邮箱 message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipient)); // 收件人邮箱 message.setSubject(subject); // 邮件主题 message.setText(body); // 邮件内容 // 发送邮件 Transport.send(message); } } ``` 这个工具使用JavaMail API发送邮件。在使用之前,你需要替换掉代码中的发件人邮箱和密码,以及邮件服务器地址和端口。使用时,只需要调用`sendEmail`方法,传入收件人邮箱、邮件主题和邮件内容即可发送邮件。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值