Java發送郵件的簡單實現

來源:互聯網
上載者:User

標籤: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發送郵件的簡單實現

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.