Sending Mail With Attachment File

Documents spreadsheets and PDF’s form.

Required Dependency

<dependency>
        <groupId>com.sun.mail</groupId>
        <artifactId>javax.mail</artifactId>
        <version>1.5.5</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi</artifactId>
        <version>3.9</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/javax.activation/activation -->
    <dependency>
        <groupId>javax.activation</groupId>
        <artifactId>activation</artifactId>
        <version>1.1.1</version>
    </dependency>

import java.io.File;
import java.io.IOException;
import java.util.Properties;

import javax.activation.CommandMap;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.activation.MailcapCommandMap;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class EmailUtil {

public static void main(String[] args) {
    System.out.println("welcome to java utility to send emails functionality");

    /* Enter UserName for authentication */
    final String username = "";
    /* Enter password for authentication */
    final String password = "";
    /* Enter host name */
    String host = "";
    /* Enter port number */
    String port = "";
    /* enter emailID who is sending */
    String emailFrom = "";
    /* Enter emailId who want to send */
    String emailToIds = "";
    /*
     * if you want to put some customer in CC then used this field it's not
     * mandatory
     */
    String emailCcIds = "";
    /*
     * if you want to put some customer in BCC then used this field it's not
     * mandatory
     */
    String emailBccIds = "";
    /* enter subject name it's like why you sending mail to customer */
    String subject = "";
    /* enter Body name it's like why you sending mail to customer */
    String body = "";
    /* if you want to send file like such as excell,world then used this field */
    String filename = "";
    File file = new File("demo.txt"); // initialize File object and passing path as argument
    boolean result;
    try {
        result = file.createNewFile(); // creates a new file
        if (result) // test if successfully created a new file
        {
            filename = file.getCanonicalPath(); // returns the path string
        }
    } catch (IOException e) {
        e.printStackTrace(); // prints exception if any
    }

    Properties prop = new Properties();
    prop.put("mail.smtp.auth", "true");
    prop.put("mail.smtp.host", host);
    prop.put("mail.smtp.port", port);
    // prop.put("mail.smtp.starttls.enable", "true");

    Session session = Session.getDefaultInstance(prop, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }
    });
    try {

        Message message = new MimeMessage(session);

        message.setFrom(new InternetAddress(emailFrom));

        if (null != emailToIds && !emailToIds.trim().isEmpty()) {
            if (emailToIds.contains(",")) {
                String to[] = emailToIds.split(",");
                InternetAddress[] toAddresses = new InternetAddress[to.length];
                for (int i = 0; i < to.length; i++) {
                    toAddresses[i] = new InternetAddress(to[i].trim());
                }
                message.setRecipients(Message.RecipientType.TO, toAddresses);
            } else {
                message.setRecipient(Message.RecipientType.TO, new InternetAddress(emailToIds));

            }

        }
        if (null != emailCcIds && !emailCcIds.trim().isEmpty()) {
            if (emailCcIds.contains(",")) {
                String cc[] = emailCcIds.split(",");
                InternetAddress[] ccAddresses = new InternetAddress[cc.length];
                for (int j = 0; j < cc.length; j++) {
                    ccAddresses[j] = new InternetAddress(cc[j].trim());
                }
                message.setRecipients(Message.RecipientType.CC, ccAddresses);
            } else {
                message.setRecipient(Message.RecipientType.CC, new InternetAddress(emailCcIds));
            }
        }
        if (null != emailBccIds && !emailBccIds.trim().isEmpty()) {
            if (emailBccIds.contains(",")) {
                String bcc[] = emailBccIds.split(",");
                InternetAddress[] bccAddresses = new InternetAddress[bcc.length];
                for (int j = 0; j < bcc.length; j++) {
                    bccAddresses[j] = new InternetAddress(bcc[j].trim());
                }
                message.setRecipients(Message.RecipientType.BCC, bccAddresses);
            } else {
                message.setRecipient(Message.RecipientType.BCC, new InternetAddress(emailBccIds));
            }

        }

        message.setSubject(subject);
        MailcapCommandMap mc = (MailcapCommandMap) CommandMap.getDefaultCommandMap();
        mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html");
        mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml");
        mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain");
        mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed");
        mc.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822");
        CommandMap.setDefaultCommandMap(mc);

        // String end = "<br><br><b>Regards,</b><br><b>VTS Team</b>";
        BodyPart messageBody = new MimeBodyPart();
        messageBody.setContent(body, "text/html");

        BodyPart messageBodyPart = new MimeBodyPart();
        Multipart multipart = new MimeMultipart();
        messageBodyPart = new MimeBodyPart();

        DataSource source = new FileDataSource(filename);
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName(filename);
        multipart.addBodyPart(messageBody);
        multipart.addBodyPart(messageBodyPart);

        message.setContent(multipart);
        Transport.send(message);
        System.out.println("Mail Sent SuccessFully");
    } catch (MessagingException e) {
        e.printStackTrace();
    }

}

}

Thanks.

About the author

ganesh

View all posts
0 0 votes
Article Rating
Subscribe
Notify of
guest
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Ravi
Ravi
3 years ago

Awesome!! Thanks a lot