Java邮件发件人工作不正常

Java邮件发件人工作不正常,java,jakarta-mail,Java,Jakarta Mail,我遇到的问题是,当我调用multipart.addBodyPartmsgbodypart时;它说,我应该在BodyPart msgbodypart=new MimeBodyPart中将msgbodypart的类型更改为MimeBodyPart;和msgbodypart=新的MimeBodyPart 好的,我改变它,然后它会删除警告: 类型Multipart中的addBodyPartBodyPart方法不适用于参数MimeBodyPart 现在怎么办 try { MimeMessage m

我遇到的问题是,当我调用multipart.addBodyPartmsgbodypart时;它说,我应该在BodyPart msgbodypart=new MimeBodyPart中将msgbodypart的类型更改为MimeBodyPart;和msgbodypart=新的MimeBodyPart

好的,我改变它,然后它会删除警告:

类型Multipart中的addBodyPartBodyPart方法不适用于参数MimeBodyPart

现在怎么办

try {
    MimeMessage msg = new MimeMessage(session);
    msg.setFrom(new InternetAddress(username));
    msg.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
    msg.setSubject("Test Java Sending Zip File");
    msg.setText("This is a message from a java program");

    BodyPart msgbodypart = new MimeBodyPart();

    msgbodypart.setText("this is msg Body");

    Multipart multipart = new MimeMultipart();

    msgbodypart = new MimeBodyPart();

    String filename = "zips.txt";

    DataSource source = new FileDataSource(filename);
    msgbodypart.setDataHandler(new DataHandler(source));
    msg.setFileName(filename);
    multipart.addBodyPart(msgbodypart);
    msg.setContent(multipart);

    System.out.println("Sending");
    Transport.send(msg);
    System.out.println("Sent!");
} catch (MessagingException mex) {
    mex.printStackTrace();
}

使用旧的lib。JavaMail API 1.4有此选项

您可能需要检查导入。确保它们都来自javax.mail。。。包装。
final Session connection = Session.getInstance(props, null);
final Message message = new MimeMessage(connection);
final BodyPart bodyPart1 = new MimeBodyPart();
final BodyPart bodyPart2 = new MimeBodyPart();
final Multipart multiPart = new MimeMultipart();
connection.setDebug(true);
try {
    final Address toAddress = new InternetAddress(
    "RECEIVER-EMAIL-ADDRESS");
    final Address fromAddress = new InternetAddress(senderUserName);
    final String content = "Please check your attachments for a zip file";

    message.setSubject("Test Java Sending Zip File");

    bodyPart1.setText(content);
    DataSource dataSource = new FileDataSource("D:\\Data.zip");
    bodyPart2.setDataHandler(new DataHandler(dataSource));
    bodyPart2.setFileName(dataSource.getName());

    multiPart.addBodyPart(bodyPart1);
    multiPart.addBodyPart(bodyPart2);
    message.setContent(multiPart);

    message.setFrom(fromAddress);
    message.setRecipient(javax.mail.Message.RecipientType.TO, toAddress);
    Transport transport = connection.getTransport("smtp");
    transport.connect(smtpServer, senderUserName, senderPassword);
    transport.sendMessage(message, message.getAllRecipients());
    System.out.println("DONE !");
} catch (AddressException e) {
    e.printStackTrace();
    throw new Exception(e);
}