JavaMail實例

//下載javamail和JAF兩個包,只要取其中的mail.jar和activaction.jar加入到庫裏面

package com.kevin;

import java.io.*;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;

 

public class MyMail{
 public static void main(String args[]) throws MessagingException,UnsupportedEncodingException {
  
  String mailuser1 = "[email protected]";
  String password1 = "******";
  
  Properties props = new Properties();
  props.put("mail.smtp.host", "smtp.163.com");
  props.put("mail.smtp.auth", "true");//設定發送郵件時需要進行身份驗證
  PopupAuthenticator auth = new PopupAuthenticator(mailuser1, password1);
  Session session = Session.getInstance(props, auth);
  MimeMessage message = new MimeMessage(session);
  Address addressFrom = new InternetAddress(mailuser1, "KevinWu");
  Address addressTo = new InternetAddress("[email protected]", "kevin wu");
  message.setText("success");
  message.setSubject("First");
  message.setFrom(addressFrom);
  message.addRecipient(Message.RecipientType.TO, addressTo);
  message.saveChanges();
  
  Transport transport = session.getTransport("smtp");
  transport.connect("smtp.163.com", mailuser1, password1);
  Transport.send(message);
  transport.close();
 }
}

class PopupAuthenticator extends Authenticator {
 private String mailuser;
 private String password;
 
 public PopupAuthenticator(String mailuser, String password){
  this.mailuser=mailuser;
  this.password=password;
 }

 public PasswordAuthentication getPasswordAuthentication() {
  return new PasswordAuthentication(mailuser, password);
 }
}

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