java - 将图片附加到使用 java 邮件 API 发送的电子邮件

标签 java api email

我有一个方法可以使用 java 发送电子邮件。我想知道如何将图片附加到电子邮件的顶部?我尝试使用 MimeMessageParts 或其他东西,但我无法让它工作?我希望能够将 BufferedImage 作为参数传递到方法中,并将其附加到顶部。任何帮助将不胜感激:)

public static void Send(final String username, final String password, 
    String recipientEmail, String ccEmail, String title, String message) 
    throws AddressException, MessagingException 
{

Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";

// Get a Properties object
Properties props = System.getProperties();
props.setProperty("mail.smtps.host", "smtp.gmail.com");
props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
props.setProperty("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.smtp.port", "465");
props.setProperty("mail.smtp.socketFactory.port", "465");
props.setProperty("mail.smtps.auth", "true");


props.put("mail.smtps.quitwait", "false");

Session session = Session.getInstance(props, null);

// -- Create a new message --
final MimeMessage msg = new MimeMessage(session);

// -- Set the FROM and TO fields --
msg.setFrom(new InternetAddress(username + "@gmail.com"));
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipientEmail, false));

if (ccEmail.length() > 0) {
    msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(ccEmail, false));
}

msg.setSubject(title);
msg.setText(message, "utf-8");
msg.setSentDate(new Date());

SMTPTransport t = (SMTPTransport)session.getTransport("smtps");

t.connect("smtp.gmail.com", username, password);
t.sendMessage(msg, msg.getAllRecipients());      
t.close();

}

最佳答案

  1. 对于附件,您需要创建单独的MimeBodyPart,这里是示例代码,

    MimeBodyPart attachmentPart = new MimeBodyPart();
    FileDataSource fileDataSource = new FileDataSource(filename) {
      @Override
     public String getContentType() {
          return "application/octet-stream";
            }
    };
    attachmentPart.setDataHandler(new DataHandler(fileDataSource));
    
  2. 对于邮件文本,您需要另一个 MimeBodyPart

    MimeBodyPart messagePart = new MimeBodyPart();
    messagePart.setText(bodyText);
    
  3. 将这两个MimeBodyPart组合成Multipart

    Multipart multipart = new MimeMultipart();
    multipart.addBodyPart(messagePart);
    multipart.addBodyPart(attachmentPart);
    
  4. 最后,发送邮件

     ...........
     final MimeMessage msg = new MimeMessage(session); 
     msg.setContent(multipart);
     Transport.send(msg);
    

有关详细信息,请参阅此 link .

关于java - 将图片附加到使用 java 邮件 API 发送的电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20527539/

相关文章:

java - 什么类型返回get方法?

java - 注册表项错误 : Java version has value '1.8' , 但需要 '1.7'

objective-c - 在 REST Api 中建模对象继承

c# - 如何在一次更新中将通过 EWS 获取的所有电子邮件标记为已读?

php - Symfony6如何正确配置sendmail从本地主机发送电子邮件

html - 表单验证 - 多封电子邮件

java - 使用 bat 文件编辑 Deployment.properties 文件

java - Java 中的括号

javascript - Youtube iFrame Api 示例 - 错误 : "JSON is undefined"?

javascript - 如何在 GraphQL 中进行相关突变?