首页 > 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学习者快速成长!