Java 封装的邮件发送类,可直接调用(基于Maven)

本文提供了一个使用JavaMail API发送带附件的HTML格式邮件的完整示例。通过AjavaSendMail工具类,实现了设置邮件内容、添加附件等功能,并演示了如何通过SMTP协议发送邮件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

maven的pom.xml中加入依赖

<span style="white-space: pre;">		</span><dependency>
			<groupId>com.sun.mail</groupId>
			<artifactId>javax.mail</artifactId>
			<version>1.5.2</version>
		</dependency>

原封不动的一个工具类


AjavaSendMail.java


import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
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 AjavaSendMail {
	private String from = "";// 发信邮箱
	public String to = "";// 收信邮箱
	public String subject = "";// 邮件主题

	private String username = "";
	private String password = "";

	public String text = "";// 邮件内容

	private Multipart mp; // 存放邮件的title 内容和附件
	private Properties props; // Properties对象
	private Message message; // Message存储发送的电子邮件信息

	public AjavaSendMail(String stmp) {
		setSmtpHost(stmp);
	}

	public void setSmtpHost(String smtpHostName) {
		System.out.println("mail.stmp.host= " + smtpHostName);
		if (props == null) {
			props = new Properties();// 创建Properties对象
		}

		props.setProperty("mail.transport.protocol", "smtp");// 设置传输协议
		props.put("mail.smtp.host", smtpHostName);// 设置发信邮箱的smtp地址"smtp.sina.com"
		props.setProperty("mail.smtp.auth", "true"); // 验证
	}

	public boolean createMimeMessage() {
		Authenticator auth = new AjavaAuthenticator(username, password); // 使用验证,创建一个Authenticator
		Session session = Session.getDefaultInstance(props, auth);// 根据Properties,Authenticator创建Session

		try {
			if (message == null) {
				message = new MimeMessage(session);// Message存储发送的电子邮件信息
			}

			message.setFrom(new InternetAddress(from));
			message.setRecipient(Message.RecipientType.TO, new InternetAddress(
					to));// 设置收信邮箱
			message.setSubject(subject);// 设置主题
			return true;
		} catch (MessagingException e) {
			e.printStackTrace();
			return false;
		}
	}

	public boolean setOut() {
		try {
			message.setContent(mp);
			message.saveChanges();// add by andy 2012-03-08
			// System.out.println("[INFO] text="+text);
			// message.setText(text);// 设置内容
			System.out.println("[INFO] 开始发送...");
			Transport.send(message);// 发送
			System.out.println("[INFO] 发送完成!");
			return true;
		} catch (Exception e) {
			System.out.println("邮箱验证出错");
			//e.printStackTrace();
			return false;
		}
	}

	public void setNamePass(String name, String pass) {
		username = name;
		password = pass;
	}

	public boolean setSubject(String mailSubject) {
		System.out.println("set title begin.");
		try {
			if (!mailSubject.equals("") && mailSubject != null) {
				subject = mailSubject;
			}
			return true;
		} catch (Exception e) {
			System.out.println("set Title faild!");
			return false;
		}
	}

	public boolean setFrom(String from) {
		System.out.println("Set From .");
		try {
			this.from = from;
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	public boolean setTo(String to) {
		System.out.println("Set to.");
		if (to == null || to.equals("")) {
			return false;
		}
		try {
			this.to = to;
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	public boolean setText(String text) {
		System.out.println("set text begin.");

		try {
			BodyPart bp = new MimeBodyPart();
			// bp.setContent("<meta http-equiv=Context-Type context=text/html;charset=gb2312>"+text,"text/html;charset=GB2312");
			bp.setContent(
					"<meta http-equiv=Context-Type context=text/html;charset=utf-8>"
							+ text, "text/html;charset=UTF-8");
			if (mp == null) {
				mp = new MimeMultipart();
			}

			mp.addBodyPart(bp);
			return true;
		} catch (Exception e) {
			System.out.println("Set context Faild! " + e);
			return false;
		}
	}

	/**
	 * 添加附件..
	 * 
	 * @param filename
	 * @return
	 */
	public boolean addFileAffix(String filename) {
		System.out.println("增加附件..");
		if (mp == null) {
			mp = new MimeMultipart();
		}
		if (filename.equals("") || filename == null) {
			return false;
		}
		String file[];
		file = filename.split(";");
		System.out.println("你有 " + file.length + " 个附件!");

		try {
			for (int i = 0; i < file.length; i++) {
				BodyPart bp = new MimeBodyPart();
				FileDataSource fileds = new FileDataSource(file[i]);
				bp.setDataHandler(new DataHandler(fileds));
				bp.setFileName(fileds.getName());

				mp.addBodyPart(bp);
			}
			return true;
		} catch (Exception e) {
			System.err.println("增加附件: " + filename + "--faild!" + e);
			return false;
		}
	}

	// 创建传入身份验证信息的 Authenticator类
	class AjavaAuthenticator extends Authenticator {
		private String user;
		private String pwd;

		public AjavaAuthenticator(String user, String pwd) {
			this.user = user;
			this.pwd = pwd;
		}

		@Override
		protected PasswordAuthentication getPasswordAuthentication() {
			return new PasswordAuthentication(user, pwd);
		}
	}

}

自己打包的,根据自己需要进行修改的第二个工具类

MailUtil.java


import org.junit.Test;

//JavaMail发送例子

public class MailUtil {
	public static final String _adminMail = "";
	public static final String _password = "";
	public static final String _stmp = "";

	public static boolean sendMail(String toMail,String title,String text){
		AjavaSendMail sm = new AjavaSendMail(_stmp);
		sm.setNamePass(_adminMail, _password);
		sm.setSubject(title);
		sm.setFrom(_adminMail);
		sm.setTo(toMail);
		sm.setText(text);
		sm.createMimeMessage();
		return sm.setOut();
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值