Sending an email with an attachment using javamail API

后端 未结 5 985
遥遥无期
遥遥无期 2020-12-06 12:10

I am trying to send an email with an attachment file in Java.

When I send the email without an attachment I receive the email, but when I add the attachment I don\'t

5条回答
  •  旧巷少年郎
    2020-12-06 12:20

    An email message consists of a header and body segment.

    Header part will contain from, to and subject.

    The body contains the attachments. To support carrying attachments in the body, type Multipart should exists.

    The Multipart object holds multiple parts in which each part is represented as a type of BodyPart whose subclass, MimeBodyPart – can take a file as its content.

    To add attachments into the mail body MimeBodyPart class provides some convenient methods.

    // JavaMail 1.3
    MimeBodyPart attachPart = new MimeBodyPart();
    String attachFile = "D:/test.pdf";
    
    DataSource source = new FileDataSource(attachFile);
    attachPart.setDataHandler(new DataHandler(source));
    attachPart.setFileName(new File(attachFile).getName());
    
    multipart.addBodyPart(attachPart);
    
    
    // JavaMail 1.4
    MimeBodyPart attachPart = new MimeBodyPart();
    String attachFile = "D:/test.pdf";
    attachPart.attachFile(attachFile);
    multipart.addBodyPart(attachPart);
    

    For more info refer this link.

    https://www.tutorialspoint.com/javamail_api/javamail_api_send_email_with_attachment.htm

提交回复
热议问题