下面是一個例子傳送一個簡單的電子郵件。在這裡,我們使用JangoSMPT伺服器通過該電子郵件被傳送到我們的目標電子郵件地址。 The setup is explained in the Environment Setup chapter.
要傳送一個簡單的電子郵件的步驟依次是:
獲取一個Session
建立一個預設 MimeMessage 物件,並設定發件人,收件人,主題(From, To, Subject)在訊息中。
將實際的訊息為:
message.setText("your text goes here");
傳送使用傳輸物件的訊息。
建立一個Java類檔案SendEmail,是其內容如下:
package com.yiibai; 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 SendEmail { public static void main(String[] args) { // Recipient's email ID needs to be mentioned. String to = "[email protected]"; // Sender's email ID needs to be mentioned String from = "[email protected]"; final String username = "manishaspatil";//change accordingly final String password = "******";//change accordingly // Assuming you are sending email through relay.jangosmtp.net String host = "relay.jangosmtp.net"; Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", host); props.put("mail.smtp.port", "25"); // Get the Session object. Session session = Session.getInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); try { // Create a default MimeMessage object. Message message = new MimeMessage(session); // Set From: header field of the header. message.setFrom(new InternetAddress(from)); // Set To: header field of the header. message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to)); // Set Subject: header field message.setSubject("Testing Subject"); // Now set the actual message message.setText("Hello, this is sample for to check send " + "email using JavaMailAPI "); // Send message Transport.send(message); System.out.println("Sent message successfully...."); } catch (MessagingException e) { throw new RuntimeException(e); } } }
由於我們使用的是由主機提供商JangoSMTP 提供 SMTP伺服器,我們需要驗證使用者名和密碼。javax.mail.PasswordAuthentication類用於驗證的密碼。
現在,我們類是準備好了,讓我們編譯上面的類。已經儲存了類SendEmail.java 到目錄:/home/manisha/JavaMailAPIExercise。我們需要jar檔案 javax.mail.jar andactivation.jar 在 classpath中。執行下面的命令從命令提示字元編譯類(jars被放置在/home/manisha/ 目錄下):
javac -cp /home/manisha/activation.jar:/home/manisha/javax.mail.jar: SendEmail.java
現在,這個類被編譯,執行下面的命令來執行:
java -cp /home/manisha/activation.jar:/home/manisha/javax.mail.jar: SendEmail
你應該看到下面的訊息命令控制台上:
Sent message successfully....
因為我通過JangoSMTP傳送郵件到我的Gmail地址,下面的郵件會在我的Gmail帳戶的收件箱中接收: