標籤:javamail
使用Oracle官方的JavaMail進行實現,JavaMail:https://java.net/projects/javamail/pages/Home
將下載好的jar包添加到工程路徑中就OK了,我使用的是最新的1.5.2版本的javax.mail.jar。
關於郵件協議可參考:什麼是POP3、SMTP和IMAP?
下面的樣本中是通過我的新浪郵箱([email protected])給QQ郵箱([email protected]不知道是誰的郵箱)發郵件,下面給出實現代碼:
import java.util.Date;import java.util.Properties;import javax.mail.Message;import javax.mail.MessagingException;import javax.mail.Session;import javax.mail.Transport;import javax.mail.internet.MimeMessage;public class SimpleMail { public static void main(String[] args) { Properties props = new Properties(); //這裡使用smtp協議發送郵件,我的新浪郵箱是.cn的不是.com的,所以smtp伺服器為smtp.sina.cn props.put("mail.smtp.host", "smtp.sina.cn"); Session session = Session.getInstance(props, null); try { MimeMessage msg = new MimeMessage(session); //設定寄件者郵箱 msg.setFrom("[email protected]"); //設定收件者郵箱 msg.setRecipients(Message.RecipientType.TO, "[email protected]"); //設定主題 msg.setSubject("This is a test"); //設定日期 msg.setSentDate(new Date()); //設定本文內容 msg.setText("How are you?\nThis is a test, please do not reply!"); //發送郵件,參數為郵件資訊,寄件者郵箱和寄件者郵箱密碼 Transport.send(msg, "[email protected]", "這裡是寄件者的密碼"); } catch (MessagingException mex) { System.err.println("Send failed! Exception: " + mex); } }}
JavaMail中比較重要的的類是Session、Store和Folder。
Java發送郵件的簡單實現