gpt4 book ai didi

java - 发送带有附件和消息的邮件

转载 作者:行者123 更新时间:2023-12-02 05:44:01 29 4
gpt4 key购买 nike

为什么无法发送消息和附件当我使用下面的代码时,它将发送邮件和附件,但不会发送消息。有人知道为什么或如何做吗?

工作代码,我使用了 Java Mail 1.4.7 jar。

import java.util.Properties;
import javax.activation.*;
import javax.mail.*;

public class MailProjectClass {

public static void main(String[] args) {

final String username = "your.mail.id@gmail.com";
final String password = "your.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("from.mail.id@gmail.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("to.mail.id@gmail.com"));
message.setSubject("Testing Subject");
message.setText("PFA");

MimeBodyPart messageBodyPart = new MimeBodyPart();

Multipart multipart = new MimeMultipart();

messageBodyPart = new MimeBodyPart();
String file = "path of file to be attached";
String fileName = "attachmentName";
DataSource source = new FileDataSource(file);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(fileName);
multipart.addBodyPart(messageBodyPart);

message.setContent(multipart);

System.out.println("Sending");

Transport.send(message);

System.out.println("Done");

} catch (MessagingException e) {
e.printStackTrace();
}
}
}

最佳答案

您需要将电子邮件正文添加为单独的多部分

String body="Email body template";
MimeBodyPart mailBody = new MimeBodyPart();
mailBody.setText(body);
multipart.addBodyPart(mailBody);

关于java - 发送带有附件和消息的邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24259966/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com