天天看點

java發送電子郵件以qq郵箱為例

需要下面兩個依賴包點選下載下傳

mail.jar

activation.jar

如何導入jar參考這裡

package com.hy.rain.controller;
import java.security.GeneralSecurityException;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import com.sun.mail.util.MailSSLSocketFactory;
public class 電子郵件 {
    public static void main(String [] args)
    {
        // 收件人電子郵箱
        String to = "[email protected]";

        // 發件人電子郵箱
        String from = "[email protected]";

        // 指定發送郵件的主機為 smtp.qq.com
        String host = "smtp.qq.com";  //QQ 郵件伺服器

        // 擷取系統屬性
        Properties properties = System.getProperties();

        // 設定郵件伺服器
        properties.setProperty("mail.smtp.host", host);

        properties.put("mail.smtp.auth", "true");
        // 擷取預設session對象
        Session session = Session.getDefaultInstance(properties,new Authenticator(){
            public PasswordAuthentication getPasswordAuthentication()
            {
                return new PasswordAuthentication("[email protected]", "授權碼"); //發件人郵件使用者名、授權碼
            }
        });

        try{
            // 建立預設的 MimeMessage 對象
            MimeMessage message = new MimeMessage(session);

            // Set From: 頭部頭字段
            message.setFrom(new InternetAddress(from));

            // Set To: 頭部頭字段
            message.addRecipient(Message.RecipientType.TO,
                    new InternetAddress(to));

            // Set Subject: 頭部頭字段
            message.setSubject("This is the Subject Line!");

            // 設定消息體
            message.setText("This is actual message");

            // 發送消息
            Transport.send(message);
            System.out.println("Sent message successfully....from runoob.com");
        }catch (MessagingException mex) {
            mex.printStackTrace();
        }
    }
}