1. 程式人生 > >java發郵件工具類

java發郵件工具類

package cn.itcast.utils;
import java.util.Properties;
	
import javax.mail.Address;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;

public class MailUtil {

//實現郵件傳送的方法
public static void sendMsg(String to ,String subject ,String content) throws Exception{
	Properties props = new Properties();
	props.setProperty("mail.smtp.host", "smtp.163.com");  //設定主機地址   smtp.qq.com    smtp.sina.com
	
	props.setProperty("mail.smtp.auth", "true");//認證 
	
	//2.產生一個用於郵件傳送的Session物件
	Session session = Session.getInstance(props);
	
	//3.產生一個郵件的訊息物件
	MimeMessage message = new MimeMessage(session);
	
	//4.設定訊息的傳送者
	Address fromAddr = new InternetAddress("
[email protected]
"); message.setFrom(fromAddr); //5.設定訊息的接收者 Address toAddr = new InternetAddress(to); //TO 直接傳送 CC抄送 BCC密送 message.setRecipient(RecipientType.TO, toAddr); //6.設定主題 message.setSubject(subject); //7.設定正文 message.setText(content); //8.準備傳送, Transport transport = session.getTransport("smtp"); //9.設定傳送目標目標 //引數2:傳送的郵箱使用者名稱 //引數3:外部發送郵件 授權密碼 transport.connect("smtp.163.com", "
[email protected]
", "XXXXX"); //10.傳送 transport.sendMessage(message, message.getAllRecipients()); //11.關閉 transport.close(); } }