普通邮件发送工具类总结

在Spring中也提供了邮件发送,如果对于不使用Spring框架的项目,邮件发送需要封装工具类

导入mail.jar和activation.jar 如果想放入web工程 需要将javaee.jar中的javax.mail和javax.activation两个不完善的工具包删除

具体代码如下:

import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;

/**
 * 发送邮件的工具类
 * 
 * @author liuxun
 *
 */
public class MailUtilsTest {
	public static void sendMail(String to, String code) throws Exception {
		Properties props = new Properties();
		// 表示SMTP发送邮件,需要进行身份验证
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.host", "smtp.126.com");
        // 发件人的账号
        props.put("mail.user", "liuxun1993728");
        // 访问SMTP服务时需要提供的密码
        props.put("mail.password", "liuxun1993728");

		// 1.Session对象.连接(与邮箱服务器连接)
		Session session = Session.getInstance(props, new Authenticator() {
			protected PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication("liuxun1993728", "liuxun1993728");
			}
		});

		// 2.构建邮件信息
		Message message = new MimeMessage(session);
		// 发件人
		message.setFrom(new InternetAddress("liuxun1993728@126.com"));
		// 收件人
		message.setRecipient(RecipientType.TO, new InternetAddress(to));
		// 设置标题
		message.setSubject("来自京亿商城的激活邮件");
		// 设置正文
		message.setContent(
				"<h1>来自京亿商城的官网激活邮件<h1><h3><a href='http://192.168.1.25:8080/myshop/user_active.action?code=" + code
						+ "'>http://192.168.1.25:8080/myshop/user_active.action?code=" + code + "</a></h3>",
				"text/html;charset=UTF-8");
	
		// 3.发送对象
		Transport.send(message);
	}
	public static void main(String[] args) throws Exception {
		sendMail("2652790899@qq.com", "123456");
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值