ChatGPT 问答00023 java代码发邮件怎么带附件

发布时间 2023-10-08 12:38:49作者: 王子健

在Java中发送带附件的Email,可以使用JavaMail和JAF(JavaBeans Activation Framework)库来实现。以下是一个基本的示例代码,演示如何发送带有附件的Email:

import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;

public class SendEmailWithAttachment {
   public static void main(String [] args) {    
      // 邮件用户名和密码
      final String username = "your_email@gmail.com";
      final String password = "your_email_password";

      // 发送邮件的配置信息
      Properties props = new Properties();
      props.put("mail.smtp.auth", "true");
      props.put("mail.smtp.starttls.enable", "true");
      props.put("mail.smtp.host", "smtp.gmail.com");
      props.put("mail.smtp.port", "587");

      // 创建一个会话,用于与邮件服务器进行通信
      Session session = Session.getInstance(props,
         new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
               return new PasswordAuthentication(username, password);
            }
         });

      try {
         // 创建一个新消息
         Message message = new MimeMessage(session);

         // 设置发送人地址
         message.setFrom(new InternetAddress("your_email@gmail.com"));

         // 设置接收人地址
         message.setRecipients(Message.RecipientType.TO,
            InternetAddress.parse("recipient_email@example.com"));

         // 设置邮件主题
         message.setSubject("Test Email with Attachment");

         // 创建一个多部分消息
         Multipart multipart = new MimeMultipart();

         // 创建邮件文本部分
         MimeBodyPart messageBodyPart = new MimeBodyPart();
         messageBodyPart.setText("This is an email with attachment.");

         // 将文本部分添加到多部分消息
         multipart.addBodyPart(messageBodyPart);

         // 创建附件部分
         MimeBodyPart attachmentBodyPart = new MimeBodyPart();
         String filename = "attachment.txt"; // 为附件文件名
         DataSource source = new FileDataSource(filename);

         // 将附件数据源添加到附件部分
         attachmentBodyPart.setDataHandler(new DataHandler(source));
         attachmentBodyPart.setFileName(filename);

         // 将附件部分添加到多部分消息
         multipart.addBodyPart(attachmentBodyPart);

         // 设置多部分消息内容
         message.setContent(multipart);

         // 发送邮件
         Transport.send(message);

         System.out.println("Email sent with attachment successfully.");

      } catch (MessagingException e) {
         throw new RuntimeException(e);
      }
   }
}

在代码中,关键是创建和设置多部分消息。首先,我们创建一个MimeMultipart对象,并将文本部分和附件部分添加到其中。然后将多部分消息设置为邮件内容。其中,附件的数据源可以从文件、字节数组或其他源获取,具体方式取决于您的需求。

另外,上述示例代码使用了Gmail SMTP服务器,并指定了需要进行身份验证和启用TLS加密协议。如果您使用其他邮件服务器,请根据实际情况修改配置信息。

需要注意的是,在使用JavaMail发送邮件时,可能会遇到网络延迟、邮箱容量限制等问题,请确保您的程序能够正确处理这些问题。