In most cases, emails are sent in a well-formatted layout following a particular template. However, various email editors do not provide the enhanced formatting options. In such cases, you can create a message in a Word document and use it as an email body. In this article, you will learn how to send an MS Word document as an email body using Java.
Java APIs to Import Word Document in Email
In order to import and send a Word document in an email body, we’ll leverage the capabilities of Aspose.Words for Java and Aspose.Email for Java APIs. The former will be used to save the Word document in MHTML format, whereas, the latter will be used to create and send the email. You can download the APIs from the following sections or install them using the Maven configurations.
<repository> <id>AsposeJavaAPI</id> <name>Aspose Java API</name> <url>https://repository.aspose.com/repo/</url> </repository>
<dependency> <groupId>com.aspose</groupId> <artifactId>aspose-words</artifactId> <version>21.4</version> <type>pom</type> </dependency> <dependency> <groupId>com.aspose</groupId> <artifactId>aspose-email</artifactId> <version>21.3</version> <classifier>jdk16</classifier> </dependency>
Send a Word Document in Email Body using Java
The following are the steps to import and send a Word document in an email body.
- Load the Word document using com.aspose.words.Document class.
- Create an instance of ByteArrayOutputStream class.
- Save the Word document as MHTML in ByteArrayOutputStream object.
- Load the MHTML in a ByteArrayInputStream object.
- Create an instance of com.aspose.email.MailMessage class and load the MHTML saved in the ByteArrayInputStream object.
- Set email’s fields such as To, From, Subject, etc.
- Create an instance of com.aspose.email.SmtpClient class
- Set the host and send the email using SmtpClient.send(MailMessage) method.
The following code sample shows how to send a Word document as an email body.
Get a Free API License
You can try the APIs used in this article without evaluation limitations by getting a free temporary license.
In this article, you have learned how to import and send a Word document as an email body using Java. Furthermore, the code sample has shown how to send the email composed of a Word document using an SMTP client. You can explore more about the APIs being used in the article by visiting the following documentations.