【问题标题】:sending mail with attachment AND a message发送带有附件和消息的邮件
【发布时间】:2014-06-17 09:17:42
【问题描述】:

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

工作代码,我用过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();
    }
  }
}

【问题讨论】:

  • 你有什么异常吗?如果是,请发布。
  • 不,我没有得到任何异常,它正常运行代码

标签: java email gmail email-attachments


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    考虑到您在这里错过了; String fileName = "attachmentName" 作为错字。

    但除此之外,您的代码运行良好。

    【讨论】:

    • 感谢您的更改,由于个人信息而编辑文本并忘记了;
    • 附件的文件格式和大小是什么?
    • .TXT 文件大小:363bytes 但如果我要使用它可以更大
    猜你喜欢
    • 2015-10-16
    • 2012-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-13
    • 1970-01-01
    相关资源
    最近更新 更多