用 Java 傳送電子郵件
- 執行 JavaMail 之前需要採取的步驟
- 用 Java 從 Gmail 傳送電子郵件
- 使用 JavaMail API 從 Microsoft 電子郵件傳送電子郵件
- 使用 Java 中的 Apache Commons 庫傳送電子郵件
本文將分享使用 JavaMail 和 Apache Commons API 傳送電子郵件的最新技術。本次演示共有三個程式。
你可以使用第一個程式從 Gmail 傳送電子郵件。第二個程式將揭示如何使用 Microsoft 以 Java 傳送電子郵件,而最後一個程式將簡單演示你如何使用 Apache Commons 使用 Java 傳送電子郵件。
執行 JavaMail 之前需要採取的步驟
- 下載並配置:JavaMail jar 檔案和啟用 jar 檔案
- 關閉兩步驗證和不太安全的應用程式
- 配置構建路徑:點選你的 Java 專案,配置構建路徑和庫部分,在 classpath 下新增外部 jar 檔案。
一旦你成功地完成了這些步驟,你的第一個程式就不會丟擲任何異常。
用 Java 從 Gmail 傳送電子郵件
在執行我們的程式之前,讓我們解釋一下程式碼是如何工作的。
Properties
:這些描述了一組永久的屬性,其中鍵是我們用來在每個鍵中設定值的字串。MimeMessage
:它包含三個重要變數,主題、收據、訊息文字。這些變數有助於獲取使用者輸入以擴充套件 MimeMessage。Session
:JavaMail API 包含會話屬性。我們也可以覆蓋會話,但這不是此任務的目標。Transport
:此 API 中的這個通用類表示傳送電子郵件的訊息傳輸功能。
程式碼:
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;
//Main Class
public class FirstProgram {
public static void main(String[] args) {
//Turn off Two Factor Authentication
//Turn off less secure app
final String sender = "Write Yor Email Address"; // The sender email
final String urpass = "The Password of your email here"; //keep it secure
Properties set = new Properties();
//Set values to the property
set.put("mail.smtp.starttls.enable", "true");
set.put("mail.smtp.auth", "true");
set.put("mail.smtp.host", "smtp.gmail.com");
set.put("mail.smtp.port", "587");
Session session = Session.getInstance(set,new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(sender, urpass);
}});
try {
//email extends Java's Message Class, check out javax.mail.Message class to read more
Message email = new MimeMessage(session);
email.setFrom(new InternetAddress("senderEmail")); //sender email address here
email.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("receiverEmail")); //Receiver email address here
email.setSubject("I am learning how to send emails using java"); //Email Subject and message
email.setText("Hi, have a nice day! ");
Transport.send(email);
System.out.println("Your email has successfully been sent!");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
輸出:
Your email has successfully been sent!
你還可以檢視以下 GIF 中的輸出:
使用 JavaMail API 從 Microsoft 電子郵件傳送電子郵件
儘管程式碼塊的核心功能與我們已經討論過的第一個程式相同,但某些功能可能會有所不同:
import java.util.Date;
:它可以生成一個日期物件並例項化它以匹配建立時間,測量到最接近的毫秒。import javax.mail.Authenticator;
:它提供了一個學習如何獲得連線身份驗證的物件。通常,這是通過向使用者提供資訊來完成的。import javax.mail.PasswordAuthentication;
:這是一個安全的容器,我們用來收集使用者名稱和密碼。注意:我們也可以根據自己的喜好覆蓋它。import javax.mail.internet.InternetAddress;
:它表示一個使用RFC822
語法結構儲存網際網路電子郵件地址的類。
javax.mail
API 中的一些類值得討論以瞭解以下程式碼結構。
程式碼:
import java.util.Date;
import java.util.Properties;
import javax.mail.Authenticator;
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 SendEmailUsingJavaOutlook {
//Define contstant strings and set properties of the email
final String SERVIDOR_SMTP = "smtp.office365.com";
final int PORTA_SERVIDOR_SMTP = 587;
final String CONTA_PADRAO = "sender email here";
final String SENHA_CONTA_PADRAO = "sender password";
final String sender = "Write your email again";
final String recvr = "Whom do you want to send?";
final String emailsubject = "Subject of the email";
//Note: you can use the date function just like these strings
final String msg = "Hi! I am sending this email from a java program.";
public void Email() {
//Set the session of email
final Session newsession = Session.getInstance(this.Eprop(), new Authenticator() {
@Override
//password authenication
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(CONTA_PADRAO, SENHA_CONTA_PADRAO);
}
});
//MimeMessage to take user input
try {
final Message newmes = new MimeMessage(newsession);
newmes.setRecipient(Message.RecipientType.TO, new InternetAddress(recvr));
newmes.setFrom(new InternetAddress(sender));
newmes.setSubject(emailsubject); //Takes email subject
newmes.setText(msg); // The main message of email
newmes.setSentDate(new Date()); //You can set the date of the email here
Transport.send(newmes);// Transfort the email
System.out.println("Email sent!");
} catch (final MessagingException ex) { //exception to catch the errors
System.out.println("try hard!"); //failed
}
}
//The permenant set of prperties containg string keys, the following configuration enables the SMPTs to function
public Properties Eprop() {
final Properties config = new Properties();
config.put("mail.smtp.auth", "true");
config.put("mail.smtp.starttls.enable", "true");
config.put("mail.smtp.host", SERVIDOR_SMTP);
config.put("mail.smtp.port", PORTA_SERVIDOR_SMTP);
return config;
}
public static void main(final String[] args) {
new SendEmailUsingJavaOutlook().Email();
}
}
輸出:
Email sent!
你還可以在下圖中檢視輸出:
使用 Java 中的 Apache Commons 庫傳送電子郵件
你可以從這裡下載 Commons Email 並將 commons-email-1.5.jar 檔案新增到你的 IDE 的構建路徑中。開啟這些庫檔案並閱讀程式碼以瞭解更多資訊。
這個最終的程式碼塊使用了所有的 Apache 類,但我們總是可以根據我們的要求定製它們。
程式碼:
import org.apache.commons.mail.DefaultAuthenticator;
import org.apache.commons.mail.Email;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.SimpleEmail;
public class SendMailWithApacheCommonsJava {
@SuppressWarnings("deprecation")
public static void main(String[] args) throws EmailException {
Email sendemail = new SimpleEmail();
sendemail.setSmtpPort(587);
sendemail.setAuthenticator(new DefaultAuthenticator("uremail","urpassword"));//password and email
sendemail.setDebug(false);
sendemail.setHostName("smtp.gmail.com");
sendemail.setFrom("uremail");
sendemail.setSubject("The subject of your email");
sendemail.setMsg("Your email Message"); Your Email Address
sendemail.addTo("receivermail"); // Receiver Email Address
sendemail.setTLS(true);
sendemail.send(); //sending email
System.out.println("You have sent the email using Apache Commons Mailing API");
}
}
輸出:
You have sent the email using Apache Commons Mailing API
你還可以在下面提供的 GIF 中看到輸出:
Sarwan Soomro is a freelance software engineer and an expert technical writer who loves writing and coding. He has 5 years of web development and 3 years of professional writing experience, and an MSs in computer science. In addition, he has numerous professional qualifications in the cloud, database, desktop, and online technologies. And has developed multi-technology programming guides for beginners and published many tech articles.
LinkedIn