javaMail的簡單應用

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();
		}
	}
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章