JavaMail Gmail SMTP服務器

在所有前面的章節中,我們使用JangoSMPT服務器來發送電子郵件。在本章中,我們將瞭解通過Gmail時提供的SMTP伺服器。 Gmail的(等等)提供了使用他們的公共SMTP服務器的免費。

Gmail SMTP服務器的詳細信息可以在這裏找到。正如你可以在細節裏看到的一樣,我們可以使用TLS或SSL連接,以通過Gmail SMTP服務器發送郵件。

使用Gmail SMTP服務器發送郵件的過程類似的發送電子郵件的章節中描述說明,除了我們改變主機服務器。作爲先決條件,發件人的電子郵件地址應該是一個活躍的Gmail帳戶。讓我們嘗試一個例子。

創建Java類

創建一個Java類文件SendEmailUsingGMailSMTP,內容都是如下:

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 SendEmailUsingGMailSMTP { public static void main(String[] args) { // Recipient's email ID needs to be mentioned. String to = "xyz@gmail.com";//change accordingly // Sender's email ID needs to be mentioned String from = "abc@gmail.com";//change accordingly final String username = "abc";//change accordingly final String password = "*****";//change accordingly // Assuming you are sending email through relay.jangosmtp.net String host = "smtp.gmail.com"; 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", "587"); // 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); } } }

主機設置爲smtp.gmail.com,端口設置爲587。在這裏,我們已經啓用TLS連接。

編譯並運行

現在,我們的類是準備好了,讓我們編譯上面的類。我已經保存了類SendEmailUsingGMailSMTP.java到目錄: /home/manisha/JavaMailAPIExercise. 我們需要 javax.mail.jar 和 activation.jar 文件在classpath中。執行下面的命令從命令提示符編譯類(jar文件放置在 /home/manisha/目錄下):

javac -cp /home/manisha/activation.jar:/home/manisha/javax.mail.jar: SendEmailUsingGMailSMTP.java

現在,這個類被編譯,執行下面的命令來運行:

java -cp /home/manisha/activation.jar:/home/manisha/javax.mail.jar: SendEmailUsingGMailSMTP

驗證輸出

你應該可以看到下面的消息命令控制檯上:

Sent message successfully....