Home > Java > javaTutorial > Sending Email Attachments in Java

Sending Email Attachments in Java

PHPz
Release: 2024-08-30 15:54:11
Original
583 people have browsed it

The following article provides an outline for Sending Email Attachments in Java. The feature of connecting an email with credentials for the email service provider is to enable the ability to send email attachments. To complete this, the email host service must be used, after which the email host, port, username, and password are entered to create the Session object. The email host service also offers all of these specifications additionally with code, that can utilize any phoney or other SMTP testing servers, and to manage the configuration and authentication for JavaMail, the session object will function as a connection factory.

Sending Email Attachments in Java

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Key Takeaways

  • JavaMail API offers various helpful classes like BodyPart, MimeBodyPart, etc. for sending emails with attachments.
  • To learn the JavaMail API’s email-sending stages before reading this example to make sense of it.
  • We must load the two jar files called mail.jar and activation.jar in order to send emails using the JavaMail API.
  • Obtain a Session and Set From, To, and Subject in the message’s default MimeMessage object.
  • MimeMultipart object creation. This multipart object should now include the messageBodyPart from above with the actual message placed in it.
  • Utilizing the Transport object, send the message.

Overview of Sending Email Attachments in Java

JavaMail API offers various helpful classes like BodyPart and MimeBodyPart for sending emails with attachments. To Learn the JavaMail API’s email-sending stages to make sense of it and should load the following two jar files in order to send emails using the JavaMail API:

  • Mail.jar
  • Activation.jar

Then let’s build MimeMessage and MimeBodyPart objects now that we have a Session object.

To generate the email message, we employ the following objects:

  • Get the compose message for the session object.
  • Create a MimeBodyPart object and specify the message text in it. Create another MimeBodyPart object and add a DataHandler object to it. Create a Multipart object and include MimeBodyPart objects in it.
  • Send a message by setting the multipart object to the message object.

Additionally, the steps in the Java email program are as follows:

  • Making an object of type javax.mail.Session.
  • The development of Javax.mail.internet.
  • MimeMessage object, in which we must set several attributes including the recipient’s email address, the email subject, the reply-to email, the email body, and attachments, among others.
  • Sending the email message using javax.mail.Transport.

How to Send Email Attachments in Java?

The credentials for the email service provider must be configured. Then, the email host, port, username, and password are entered to build the Session object. The email host service offers all of these specifics. For the code, we can utilize any phoney SMTP testing servers. To manage the configuration and authentication for JavaMail, the session object will function as a connection factory. To build MimeMessage and MimeBodyPart objects now that we have a Session object. To generate the email message, we employ the following objects:

Code:

Message testmsg = new MimeMessage(sess);
testmsg.setFrom(new InternetAddress(fromaddr));
testmsg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
testmsg.setSubject("Welcome to our Test Site");
Copy after login

The above code helps to create the Message service with help of MimeMessage session object. So that we can pass the session(sess) as the parameter for the Message queue. With the help of instance, we can call the method called setFrom() so used to pass the From address or senders list. In the same instance, we can call the other method called setRecipients() with parameter passing like Message class with an additional method called RecipientType with calling To mail receivers and additionally InternetAddress with default method called parse(to) for passing the to address Recipients. The setSubject() is passing the string values in the Message class instance. The MimeMessage object has been generated in the excerpt above with the necessary information, including from, to, and subject. Next, we have a MimeBodyPart object that contains the email body. Additionally, to add an attachment to the mail service, we should now build another MimeBodyPart.

Code:

MimeBodyPart mpart = new MimeBodyPart();
mpart.attachFile(new File("path/to/file"));
Copy after login

The MimeBodyPart is the mail class body that created the instance and the same will be called for the method called attachFile() with additional parameters like to pass the new File object creation with file path parameters. TLS authentication is possible but different in several ways. As we can see, we are calling additional EmailUtil class methods to deliver email attachments and images even though we haven’t yet defined them.

Example of Sending Email Attachments in Java

Given below is the example mentioned:

Code:

package TestNG;
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.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 NewTest{
public static void main(String[] args) throws Exception {
Properties props = new Properties();
props.setProperty("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
props.put("mail.debug", "true");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
Session sess = Session.<em><i>getDefaultInstance</i></em>(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("[email protected]","xodbizaoiqijifre");
}
});
try{
MimeMessage msg = new MimeMessage(sess);
msg.setFrom(new InternetAddress("[email protected]"));
msg.addRecipient(Message.RecipientType.<em><i>TO</i></em>,new InternetAddress("[email protected]"));
msg.setSubject("Welcome To My Domain");
BodyPart mbody = new MimeBodyPart();
mbody.setText("Your Message body is sent");
MimeBodyPart mbody1 = new MimeBodyPart();
String filename = "D://articles1.txt";
DataSource source = new FileDataSource(filename);
mbody1.setDataHandler(new DataHandler(source));
mbody1.setFileName(filename);
Multipart mpart = new MimeMultipart();
mpart.addBodyPart(mbody);
mpart.addBodyPart(mbody1);
msg.setContent(mpart );
Transport.<em><i>send</i></em>(msg);
System.<em><i>out</i></em>.println("Your email is sent successfully");
}catch (MessagingException ex) {ex.printStackTrace();}
}
}
Copy after login

Output:

Sending Email Attachments in Java

  • In the above example, we first set the properties class and call the required mail.smtp.host parameters.
  • By using the session class instance, we can call and validate the user details like username and password.
  • Default session class creation like MimeMessage, MimeBodyPart, and Multipart to connect the user communications.
  • Using try and catch block to get the exception if the condition is not satisfied.
  • The transport protocol and its method for sending the message along with the attachment.

FAQs

Given below are the FAQs mentioned:

Q1. Define sending email with an attachment.

Answer: When enabling the functionality of sending email attachments, the email host, port, username, and password are entered after configuring the email with the email service provider’s credentials.

Q2. What is MimeMultipart in Java?

Answer: The abstract Multipart class is implemented by the MimeMultipart class, which employs MIME standards for multipart data.

Q3. What are the steps to follow sending email with an attachment?

Answer: Get the compose message for the session object.

Create a MimeBodyPart object and specify the message text in it. Create another MimeBodyPart object and add a DataHandler object to it. Create a Multipart object and include MimeBodyPart objects in it.

Send a message by setting the multipart object to the message object.

Conclusion

To obtain the session object, which contains all of the host’s data, including hostname, username, and password. Write the message, the message along with the attachment, and send it. The JavaMail API provides a platform- and protocol-neutral foundation for building mail and messaging applications. The JavaMail API makes a number of abstract classes defining the components of a mail system available.

The above is the detailed content of Sending Email Attachments in Java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template