How to send email with attachment using JAVA Mail API ?

java_logo

For sending the email using JAVA Mail API, you need to add following jar files:
1. mail.jar
2. activation.jar 
Download jar files
you can download these jars here
You need to add mail.jar and activation.jar  files in your CLASSPATH.

Here is the example for sending email with attachment 


package com.techspace;
import java.util.Calendar;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Multipart;
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 MailSend {
public static String senderName = "Technology Space"; //change according to need
public static String hostName = "smtp.gmail.com"; //change according to need
public static String fromMailId = "admin@techspace.com"; //change according to need
public static String password = "admin12345"; //change according to need
public static String authentication = "true";
public static String portNumber = "25"; //change according to need
public static String protocol = "smtp";

public static void main(String[] args) {

String to = "abc@gmail.com";
String subject = "Technology Space Articles Details";
String body = "Hello Dear, How are you?";
String filename = "D:\\tech.txt"; //change according to need
Properties props = null;
Transport t = null;
MimeMessage message = null;
try {
// Get system properties
props = System.getProperties();
// Setup mail server
props.put("mail.smtp.starttls.enable", authentication);
props.put("mail.smtp.host", hostName);
props.put("mail.smtp.port", portNumber);
props.put("mail.smtp.auth", authentication);
props.put("mail.smtp.user", fromMailId);
props.put("mail.smtp.password", password);
// Get session
javax.mail.Session mailSession = javax.mail.Session.getInstance(props, null);
// Define message
message = new MimeMessage(mailSession);
// create the message part
BodyPart messageBodyPart = new MimeBodyPart();
//set message here
messageBodyPart.setText(body);
//create MimeMultipart object and set Data Handler and then set File Name
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
// Put multipart object in message object
message.setContent(multipart);

Calendar today = Calendar.getInstance();
// Now compose message by setting all necessary details
message.setSentDate(today.getTime());
message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setFrom(new InternetAddress(senderName + "<" + fromMailId + ">"));

message.setSubject(subject);
message.saveChanges();
t = mailSession.getTransport(protocol);
t.connect(hostName, fromMailId, password);
// Send the message
t.sendMessage(message, message.getAllRecipients());
if (t != null) {
System.out.println("Email Sent Successfully");
}
} catch (Exception e) {
System.out.println("Exception in MailSend() :"+ e);
}

}
}

Download Source Code


Thank you for read this tutorial. See you in next tutorial.
Share on Google Plus

About JK STACK

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.

2 comments:

  1. To send an email with an attachment using the JavaMail API, you can follow these steps. This example uses the JavaMail library, which you'll need to include in your project's dependencies.

    Step 1: Set Up Your Development Environment

    Make sure you have the JavaMail library added to your project's dependencies. You can download the JavaMail library from the Oracle website or include it as a Maven or Gradle dependency.

    Step 2: Import Required Classes

    In your Java code, import the necessary classes from the JavaMail library and other standard Java libraries:

    java
    Copy code
    import javax.mail.*;
    import javax.mail.internet.*;
    import java.util.*;
    Step 3: Create an Email Session

    Create a session for sending emails. You'll need to provide the email server settings and authentication information if required. Here's an example:

    java
    Copy code
    Properties properties = new Properties();
    properties.put("mail.smtp.host", "smtp.example.com"); // Replace with your SMTP server
    properties.put("mail.smtp.port", "587"); // Replace with your SMTP port
    properties.put("mail.smtp.auth", "true"); // Enable authentication

    // If you need to use TLS, uncomment the following line:
    // properties.put("mail.smtp.starttls.enable", "true");

    Session session = Session.getInstance(properties, new Authenticator() {
    protected PasswordAuthentication getPasswordAuthentication() {
    return new PasswordAuthentication("your_email@example.com", "your_password");
    }
    });
    Replace "smtp.example.com", "587", "your_email@example.com", and "your_password" with your SMTP server details and email credentials.

    Step 4: Create the Email Message

    Compose the email message, including the recipient, subject, and message body:

    java
    Copy code
    try {
    Message message = new MimeMessage(session);
    message.setFrom(new InternetAddress("your_email@example.com"));
    message.setRecipient(Message.RecipientType.TO, new InternetAddress("recipient@example.com")); // Replace with the recipient's email
    message.setSubject("Subject of the Email");
    message.setText("Hello, this is the message body.");

    // Create and attach the file
    MimeBodyPart attachmentPart = new MimeBodyPart();
    String filename = "path_to_your_file.txt"; // Replace with the path to your file
    DataSource source = new FileDataSource(filename);
    attachmentPart.setDataHandler(new DataHandler(source));
    attachmentPart.setFileName("file.txt"); // Rename the attached file as needed

    // Create a multipart message
    Multipart multipart = new MimeMultipart();
    multipart.addBodyPart(attachmentPart);

    // Set the message content to be the multipart message
    message.setContent(multipart);

    // Send the email
    Transport.send(message);
    System.out.println("Email sent successfully!");
    } catch (MessagingException e) {
    e.printStackTrace();
    }
    Step 5: Run Your Code

    Execute your Java code to send the email with the attachment. Ensure that the file you want to attach exists at the specified path.

    This example demonstrates how to send a basic email with an attachment using JavaMail. You can further customize the email, add multiple recipients, and handle exceptions for more robust email functionality.
    Regrds: Cracksnoon

    ReplyDelete
  2. >Upgrade your surveillance game with cutting-edge security solutions! Our High-Speed Dome Cameras redefine vigilance, offering swift and precise monitoring. Experience 360-degree coverage, powerful zoom capabilities, and rapid response times. Secure your space with state-of-the-art technology. Elevate your security – invest in the future. Explore the possibilities today for unparalleled peace of mind. Your safety deserves nothing but the best. Upgrade to high-speed precision! 🌐👁️🔒

    ReplyDelete