在这个简短的主题中,您将了解如何**使用 Java **在电子邮件中发送 Word Document。您可以使用简单的 API 调用轻松地将源文件转换为 MHTML 格式并指定电子邮件设置以在任何常见操作系统(如 MS Windows、Ubuntu 或 macOS)中发送电子邮件。
使用 Java 在电子邮件中发送 Word 文档的步骤
- 从 Maven 存储库添加 Aspose.Words 和 Aspose.Email JAR 文件引用
- 实例化一个 Document Class 对象以加载输入文档以发送电子邮件
- 指定不同的 SaveOptions 以 MHTML 格式保存文件以将数据保存到流中
- 使用 MailMessage 类加载文件
- 初始化 SMTP 客户端以配置电子邮件消息
- 发送包含 word 文档的电子邮件
在这些步骤中,首先我们以 DOCX 或 DOC 文件格式加载输入的 Word 文档。然后使用流对象将其转换为 MHTML 文件,该流对象作为输入文件加载以发送电子邮件。最后,我们指定发送者、主题、端口等配置属性来发送电子邮件。
使用 Java 在电子邮件中发送 DOCX 的代码
import com.aspose.words.Document; | |
import com.aspose.words.License; | |
import com.aspose.words.SaveFormat; | |
import com.aspose.email.MailMessage; | |
import com.aspose.email.SmtpClient; | |
import com.aspose.email.SecurityOptions; | |
public class SendWordocumentInEmailJava { | |
public static void main(String[] args) throws Exception { // main method for sending word document in email using Java | |
// Set Aspose.Words license before converting sending word document in email using Java | |
License WordLicense = new License(); | |
WordLicense.setLicense("Aspose.Word.lic"); | |
License EmailLicense = new EmailLicense(); | |
EmailLicense.setLicense("Aspose.Email.lic"); | |
// Load the document for sending as email using Document class | |
Document EmaiDocument = new Document("EmailTest.docx"); | |
SaveOptions options = null; | |
options.setSaveFormat(SaveFormat.MHTML); | |
// Convert the document to MHTML format by using memory stream | |
ByteArrayOutputStream EmailStream = new ByteArrayOutputStream(); | |
EmaiDocument.save(EmailStream, options); | |
ByteArrayInputStream stream = new ByteArrayInputStream(EmailStream.toByteArray()); | |
// Create an Aspose.Email message from the saved stream | |
com.aspose.email.MailMessage EmailMessage = | |
com.aspose.email.MailMessage.load(stream, new com.aspose.email.MhtmlLoadOptions()); | |
// Set properties of email to send | |
EmailMessage.setFrom(com.aspose.email.MailAddress.to_MailAddress("sender@sender.com")); | |
EmailMessage.getTo().add("your_to_email@email.com"); | |
EmailMessage.setSubject("Test Message for testing Aspose.Words and Aspose.Email APIs"); | |
// Initialize SMTP client and it's properties to send email | |
SmtpClient SMTPClient = new SmtpClient(); | |
SMTPClient.setHost("smtp.gmail.com"); | |
SMTPClient.setUsername("YourEmail@gmail.com"); | |
SMTPClient.setPassword("Your Gamil Password"); | |
SMTPClient.setPort(587); | |
SMTPClient.setSecurityOptions(SSLExplicit); | |
// Send word email message | |
SMTPClient.send(EmailMessage); | |
} | |
} |
在上面的代码片段中,我们在使用 Document 类 的对象时加载了源 DOCX 文件。然后使用流将其转换为 MHTML 文件,稍后由 Aspose.Email 处理。然后我们设置不同的发送电子邮件信息的首选项,例如电子邮件地址、电子邮件地址、主题和主机设置,以控制电子邮件信息属性。这使您能够自动化电子邮件发送功能并使用 Java 在电子邮件中发送文档。
之前,我们了解了 如何使用 Java 将 Word 转换为 Markdown。然而,在本主题中,我们专注于将 DOCX 渲染为 TIFF。然而,在本主题中,我们学习了如何使用 Java 在电子邮件中发送 Word 文档。