Skip to content Skip to sidebar Skip to footer

Sending Email As Attachment In Java

I have an image in my d drive and i want to send it as an email attachment in java. Recipients mail will be entered by sender, I just want to attach it to my email account. Please

Solution 1:

Check out the link(my answer to that question) for email sending utility code. You've got to add few line of code to send mail with attachment.

On submit the information should come to email

In EmailUtility.java after

msg.setSentDate(new Date());

comment

msg.setText(message); 

And add the following code:

     // creates message part
    MimeBodyPart messageBodyPart = new MimeBodyPart();
    messageBodyPart.setContent(message, "text/html");
    String attachFile = "C:/imgname.jpg";
    // creates multi-part
    Multipart multipart = new MimeMultipart();
    multipart.addBodyPart(messageBodyPart);
    // adds attachments

    if(reason.equals("attach"))
    if (attachFile != null) {
            MimeBodyPart attachPart = new MimeBodyPart();
            attachPart.attachFile(attachFile);
            multipart.addBodyPart(attachPart);
    }

    // sets the multi-part as e-mail's content
    msg.setContent(multipart);

You've got to change C:/imgname.jpg to your file name along with its path.


Post a Comment for "Sending Email As Attachment In Java"