Java發送郵件

package com.zhx;

import java.util.Properties;

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;

public class Mail
{

    public static void main(String[] args)
    {
        String mailForm = "zzz";//發出郵件的地址
        String passWord = "xxx";//發出郵件的密碼
        String host = "smtp.163.com";//發送郵件的服務器地址,以163郵箱爲例,服務器地址爲smtp.163.com
        String mailTo = "vvv";//發送郵件的地址
        
        //發送郵件的內容
        String content = "asdf";
        // 創建一個配置文件並保存
        Properties properties = new Properties();
        // 發送服務器需要身份驗證
        properties.setProperty("mail.smtp.auth", "true");
        // 設置郵件服務器主機名
        properties.setProperty("mail.host", host);
        // 發送郵件協議名稱
        properties.setProperty("mail.transport.protocol", "smtp");

        try
        {
            // 設置環境信息
            Session localSession = Session.getInstance(properties, new javax.mail.Authenticator() {
                // 在session中設置賬戶信息,Transport發送郵件時會使用
                protected PasswordAuthentication getPasswordAuthentication()
                {
                    return new PasswordAuthentication(mailForm, passWord);
                }
            });
            // 創建郵件對象
            Message msg = new MimeMessage(localSession);
            // 發件人
            msg.setFrom(new InternetAddress(mailForm));
            // 收件人
            msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(mailTo));
            // 主題
            msg.setSubject("qwer");
            // HTML內容
            msg.setContent(content, "text/html;charset=utf-8");
            Transport.send(msg);
        }
        catch (MessagingException e)
        {
            e.printStackTrace();
        }
    }

}
 

以上爲jmail依賴發送郵件的代碼

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