Send email with attachment using JavaMail API

We are explaining here an example of sending email with attachment using JavaMail API.

Steps of sending email with attachment using JavaMail API:

    1. Get a session instance from getDefaultInstance() or getInstance() method of Session class.
    2. Create a message we have to pass session object in MimeMessage class constructor.
    3. Use the InternetAddress class to set the information of sender and recipient.
    4. Create the MimeBodyPart object and set actual message.
    5. Create DataHandler object and set attachment in it.
    6. Create a new MimeBodyPart object and set DataHandler object in it.
    7. Create a MimeMultipart object and set MimeBodyPart objects in it.
    8. Set the multipart object in the message object.
    9. Use send() method of javax.mail.Transport class to send the message.

Example:

SendEmailWthAttachment.java
import javax.activation.*;
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
/**
* This class is used to send email with attachment.
* @author javawithease
*/

public class SendEmailWthAttachment {
final String senderEmailId = "jaisingh@javawithease.com";
final String senderPassword = "****";
final String emailSMTPserver = "smtpout.secureserver.net";
 
public SendEmailWthAttachment (String receiverEmail,
String subject, String messageText,
String fileName, String filePath) {
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.host", emailSMTPserver);
 
try {
Authenticator auth = new SMTPAuthenticator();
Session session = Session.getInstance(props, auth);
 
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(senderEmailId));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(receiverEmail));
message.setSubject(subject);
 
MimeBodyPart messageBodyPart1 = new MimeBodyPart();
messageBodyPart1.setText(messageText);
MimeBodyPart messageBodyPart2 = new MimeBodyPart();
DataSource source = new FileDataSource(filePath);
messageBodyPart2.setDataHandler(new DataHandler(source));
messageBodyPart2.setFileName(fileName);
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart1);
multipart.addBodyPart(messageBodyPart2);
message.setContent(multipart);
message.setText(messageText);
 
Transport.send(message);
 
System.out.println("Email send successfully.");
} catch (Exception e) {
System.err.println("Error in sending email.");
}
}
 
private class SMTPAuthenticator extends
javax.mail.Authenticator {
public PasswordAuthentication
getPasswordAuthentication() {
return new PasswordAuthentication(senderEmailId,
senderPassword);
}
}
 
public static void main(String[] args) {
new SendEmailWthAttachment ("javawithease@gmail.com",
"Test Email", "Hi,\n\n This is a test email " +
"with attachment.", "D:\\test.txt", "test.txt");
}
}

Output:

Email send successfully.

No comments: