// 傳送郵件
public static void send(String toEmail, String content) {
Session session = getSession();
try {
System.out.println("--send--" + content);
// Instantiate a message
Message msg = new MimeMessage(session); // Set message attributes
msg.setFrom(new InternetAddress("[email protected]"));//發件人地址
InternetAddress[] address = { new InternetAddress("[email protected]") };
msg.setRecipients(Message.RecipientType.TO, address);// 收件人地址
msg.setSubject("這是發生的主題");// 傳送的主題
msg.setSentDate(new Date());// 傳送日期
msg.setContent("這是發生的內容", "text/html;charset=utf-8");// 傳送型別 // Send the message
Transport.send(msg);
} catch (MessagingException mex) {
mex.printStackTrace();
}
} private static Session getSession() {
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.qq.com");// 設定伺服器地址
props.put("mail.store.protocol", "smtp");// 設定協議
props.put("mail.smtp.port", 25);// 設定埠
props.put("mail.smtp.auth", "true");// 一定要這麼設定,驗證"true",不能設定為true
// 建立一個密碼驗證器
Authenticator authenticator = new Authenticator() { @Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("[email protected]", "****");//傳送郵件的賬戶和密碼
} };
// 根據郵件會話屬性和密碼驗證器構造一個傳送郵件的session
Session session = Session.getDefaultInstance(props, authenticator); return session;
}

我用的是mail.jar和activation-1.1.1.jar。

傳送者郵箱需要開啟POP3/SMTP服務和IMAP/SMTP服務。qq郵箱傳送,設定服務的時候需要設定獨立密碼,上面使用的驗證密碼就是這個獨立密碼,使用qq郵箱的登入密碼是不行的。否則會報:535 Authentication failed 這個錯誤。

呼叫上面的send方法,把要接受郵箱的地址和內容傳過來就可以。