---
title: "javaMail的简单应用"
author: "qdexception"
date: "2010-04-29T22:03:12Z"
tags: []
categories: ["编程语言"]
slug: "javamail"
draft: false
lastmod: "2010-04-29T22:03:12Z"
id: 656563
url: "https://qdexception.iteye.com/blog/656563"
---

import javax.mail.*;
import java.util.*;
import javax.mail.internet.*;
public class Mail_Sender {
	public void send(String email,String username,String password)
	{
		Properties p = System.getProperties();
		//设置SMTP服务器
		p.setProperty("mail.smtp.host","smtp服务器");
		//验证SMTP
		p.put("mail.smtp.auto","true");
		Session s = Session.getInstance(p);
		//查看运行时信息
		//s.setDebug(true);
		//由邮件Session新建一个消息对象
		MimeMessage mm = new MimeMessage(s);
		try
		{
			//发件人
			InternetAddress from = new InternetAddress("发件人地址");
			mm.setFrom(from);
			
			//收件人
			InternetAddress to = new InternetAddress(email);
			mm.setRecipient(Message.RecipientType.TO,to);
			
			//邮件标题
			mm.setSubject("标题");
			String content="尊敬的用户:"+username+",您的新密码为:"+password+",请妥善保管!";
			
			//邮件内容
			mm.setContent(content,"text/html;charset=UTF-8");
			
			//保存
			mm.saveChanges();
			
			Transport tr = s.getTransport("smtp");
			
			//smtp验证，也就是你要用来发邮件的那个邮箱的名字密码
			tr.connect("smtp服务器","用户名","密码");
			
			//发送
			tr.sendMessage(mm,mm.getAllRecipients());
			tr.close();
		}catch(Exception e)
		{
			e.printStackTrace();
		}
	}
}