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();
// 發送伺服器需要身份驗證,有些可能會存在沒有密碼的情況,可以設定為false,不進行密碼校驗
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依賴發送郵件的代碼