Sending mail attachment using Java Sending mail attachment using Java java java

Sending mail attachment using Java


Working code, I have used 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();                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();    }  }}


For an unknow reason, the accepted answer partially works when I send email to my gmail address. I have the attachement but not the text of the email.

If you want both attachment and text try this based on the accepted answer :

    Properties props = new java.util.Properties();    props.put("mail.smtp.host", "yourHost");    props.put("mail.smtp.port", "yourHostPort");    props.put("mail.smtp.auth", "true");                 props.put("mail.smtp.starttls.enable", "true");    // Session session = Session.getDefaultInstance(props, null);    Session session = Session.getInstance(props,              new javax.mail.Authenticator() {                protected PasswordAuthentication getPasswordAuthentication() {                    return new PasswordAuthentication("user", "password");                }              });    Message msg = new MimeMessage(session);    try {        msg.setFrom(new InternetAddress(mailFrom));        msg.setRecipient(Message.RecipientType.TO, new InternetAddress(mailTo));        msg.setSubject("your subject");        Multipart multipart = new MimeMultipart();        MimeBodyPart textBodyPart = new MimeBodyPart();        textBodyPart.setText("your text");        MimeBodyPart attachmentBodyPart= new MimeBodyPart();        DataSource source = new FileDataSource(attachementPath); // ex : "C:\\test.pdf"        attachmentBodyPart.setDataHandler(new DataHandler(source));        attachmentBodyPart.setFileName(fileName); // ex : "test.pdf"        multipart.addBodyPart(textBodyPart);  // add the text part        multipart.addBodyPart(attachmentBodyPart); // add the attachement part        msg.setContent(multipart);        Transport.send(msg);    } catch (MessagingException e) {        LOGGER.log(Level.SEVERE,"Error while sending email",e);    }

Update :

If you want to send a mail as an html content formated you have to do

    MimeBodyPart textBodyPart = new MimeBodyPart();    textBodyPart.setContent(content, "text/html");

So basically setText is for raw text and will be well display on every server email including gmail, setContent is more for an html template and if you content is formatted as html it will maybe also works in gmail


Using Spring Framework , you can add many attachments :

package com.mkyong.common;import javax.mail.MessagingException;import javax.mail.internet.MimeMessage;import org.springframework.core.io.FileSystemResource;import org.springframework.mail.MailParseException;import org.springframework.mail.SimpleMailMessage;import org.springframework.mail.javamail.JavaMailSender;import org.springframework.mail.javamail.MimeMessageHelper;public class MailMail{    private JavaMailSender mailSender;    private SimpleMailMessage simpleMailMessage;    public void setSimpleMailMessage(SimpleMailMessage simpleMailMessage) {        this.simpleMailMessage = simpleMailMessage;    }    public void setMailSender(JavaMailSender mailSender) {        this.mailSender = mailSender;    }    public void sendMail(String dear, String content) {       MimeMessage message = mailSender.createMimeMessage();       try{        MimeMessageHelper helper = new MimeMessageHelper(message, true);        helper.setFrom(simpleMailMessage.getFrom());        helper.setTo(simpleMailMessage.getTo());        helper.setSubject(simpleMailMessage.getSubject());        helper.setText(String.format(            simpleMailMessage.getText(), dear, content));        FileSystemResource file = new FileSystemResource("/home/abdennour/Documents/cv.pdf");        helper.addAttachment(file.getFilename(), file);         }catch (MessagingException e) {        throw new MailParseException(e);         }         mailSender.send(message);         }}

To know how to configure your project to deal with this code , complete reading this tutorial .