首頁 > Java > java教程 > 主體

用Java發送電子郵件附件

PHPz
發布: 2024-08-30 15:54:11
原創
479 人瀏覽過

以下文章提供了用 Java 發送電子郵件附件的概述。將電子郵件與電子郵件服務提供者的憑證連接起來的功能是啟用發送電子郵件附件的功能。若要完成此操作,必須使用電子郵件主機服務,然後輸入電子郵件主機、連接埠、使用者名稱和密碼來建立 Session 物件。電子郵件主機服務還額外提供所有這些規格和程式碼,可以利用任何虛假或其他 SMTP 測試伺服器,並管理 JavaMail 的設定和驗證,會話物件將充當連接工廠。

用Java發送電子郵件附件

開始您的免費軟體開發課程

網頁開發、程式語言、軟體測試及其他

要點

  • JavaMail API 提供了各種有用的類,如 BodyPart、MimeBodyPart 等,用於發送帶有附件的電子郵件。
  • 在閱讀此範例以理解它之前,先了解 JavaMail API 的電子郵件發送階段。
  • 我們必須載入兩個名為mail.jar 和activation.jar 的jar 檔案才能使用JavaMail API 發送電子郵件。
  • 取得會話並在訊息的預設 MimeMessage 物件中設定 From、To 和主題。
  • MimeMultipart 物件建立。這個多部分物件現在應該包含上面的 messageBodyPart 以及放置在其中的實際訊息。
  • 利用 Transport 對象,發送訊息。

Java 發送電子郵件附件概述

JavaMail API 提供了各種有用的類,例如 BodyPart 和 MimeBodyPart,用於發送帶有附件的電子郵件。要了解 JavaMail API 的電子郵件發送階段並理解它,應加載以下兩個 jar 檔案以便使用 JavaMail API 發送電子郵件:

  • Mail.jar
  • 啟動.jar

既然我們已經有了 Session 對象,那麼讓我們建立 MimeMessage 和 MimeBodyPart 物件。

為了產生電子郵件訊息,我們使用以下物件:

  • 取得會話物件的撰寫訊息。
  • 建立一個 MimeBodyPart 物件並在其中指定訊息文字。建立另一個 MimeBodyPart 物件並向其新增一個 DataHandler 物件。建立一個 Multipart 物件並在其中包含 MimeBodyPart 物件。
  • 透過將多部分物件設定為訊息物件來傳送訊息。

另外,Java電子郵件程式中的步驟如下:

  • 建立 javax.mail.Session 類型的物件。
  • Javax.mail.internet 的開發。
  • MimeMessage 對象,我們必須在其中設定幾個屬性,包括收件者的電子郵件地址、電子郵件主題、回覆電子郵件、電子郵件正文和附件等。
  • 使用 javax.mail.Transport 傳送電子郵件。

如何用Java傳送電子郵件附件?

必須設定電子郵件服務提供者的憑證。然後,輸入電子郵件主機、連接埠、使用者名稱和密碼來建立會話物件。電子郵件主機服務提供所有這些細節。對於程式碼,我們可以利用任何虛假的 SMTP 測試伺服器。為了管理 JavaMail 的配置和身份驗證,會話物件將充當連接工廠。現在我們已經有了 Session 對象,可以建立 MimeMessage 和 MimeBodyPart 物件。為了產生電子郵件訊息,我們使用以下物件:

代碼:

Message testmsg = new MimeMessage(sess);
testmsg.setFrom(new InternetAddress(fromaddr));
testmsg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
testmsg.setSubject("Welcome to our Test Site");
登入後複製

上面的程式碼有助於在 MimeMessage 會話物件的幫助下建立訊息服務。這樣我們就可以將會話(sess)作為訊息佇列的參數傳遞。在實例的幫助下,我們可以呼叫名為 setFrom() 的方法,用於傳遞寄件者地址或寄件者清單。在同一個實例中,我們可以呼叫另一個名為setRecipients() 的方法,它具有像Message 類別一樣的參數傳遞,並具有一個名為RecipientType 的附加方法,用於呼叫To 郵件接收者,此外還可以呼叫InternetAddress 以及名為parse(to) 的預設方法,用於傳遞目標位址收件者。 setSubject() 在 Message 類別實例中傳遞字串值。上面的摘錄中已產生 MimeMessage 對象,其中包含必要的訊息,包括寄件者、收件者和主題。接下來,我們有一個包含電子郵件正文的 MimeBodyPart 物件。此外,要為郵件服務新增附件,我們現在應該建立另一個 MimeBodyPart。

代碼:

MimeBodyPart mpart = new MimeBodyPart();
mpart.attachFile(new File("path/to/file"));
登入後複製

The MimeBodyPart is the mail class body that created the instance and the same will be called for the method called attachFile() with additional parameters like to pass the new File object creation with file path parameters. TLS authentication is possible but different in several ways. As we can see, we are calling additional EmailUtil class methods to deliver email attachments and images even though we haven’t yet defined them.

Example of Sending Email Attachments in Java

Given below is the example mentioned:

Code:

package TestNG;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
public class NewTest{
public static void main(String[] args) throws Exception {
Properties props = new Properties();
props.setProperty("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
props.put("mail.debug", "true");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
Session sess = Session.<em><i>getDefaultInstance</i></em>(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("[email protected]","xodbizaoiqijifre");
}
});
try{
MimeMessage msg = new MimeMessage(sess);
msg.setFrom(new InternetAddress("[email protected]"));
msg.addRecipient(Message.RecipientType.<em><i>TO</i></em>,new InternetAddress("[email protected]"));
msg.setSubject("Welcome To My Domain");
BodyPart mbody = new MimeBodyPart();
mbody.setText("Your Message body is sent");
MimeBodyPart mbody1 = new MimeBodyPart();
String filename = "D://articles1.txt";
DataSource source = new FileDataSource(filename);
mbody1.setDataHandler(new DataHandler(source));
mbody1.setFileName(filename);
Multipart mpart = new MimeMultipart();
mpart.addBodyPart(mbody);
mpart.addBodyPart(mbody1);
msg.setContent(mpart );
Transport.<em><i>send</i></em>(msg);
System.<em><i>out</i></em>.println("Your email is sent successfully");
}catch (MessagingException ex) {ex.printStackTrace();}
}
}
登入後複製

Output:

用Java發送電子郵件附件

  • In the above example, we first set the properties class and call the required mail.smtp.host parameters.
  • By using the session class instance, we can call and validate the user details like username and password.
  • Default session class creation like MimeMessage, MimeBodyPart, and Multipart to connect the user communications.
  • Using try and catch block to get the exception if the condition is not satisfied.
  • The transport protocol and its method for sending the message along with the attachment.

FAQs

Given below are the FAQs mentioned:

Q1. Define sending email with an attachment.

Answer: When enabling the functionality of sending email attachments, the email host, port, username, and password are entered after configuring the email with the email service provider’s credentials.

Q2. What is MimeMultipart in Java?

Answer: The abstract Multipart class is implemented by the MimeMultipart class, which employs MIME standards for multipart data.

Q3. What are the steps to follow sending email with an attachment?

Answer: Get the compose message for the session object.

Create a MimeBodyPart object and specify the message text in it. Create another MimeBodyPart object and add a DataHandler object to it. Create a Multipart object and include MimeBodyPart objects in it.

Send a message by setting the multipart object to the message object.

Conclusion

To obtain the session object, which contains all of the host’s data, including hostname, username, and password. Write the message, the message along with the attachment, and send it. The JavaMail API provides a platform- and protocol-neutral foundation for building mail and messaging applications. The JavaMail API makes a number of abstract classes defining the components of a mail system available.

以上是用Java發送電子郵件附件的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!