Home >Java >javaTutorial >Sending Email Attachments in Java
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.
Start Your Free Software Development Course
Web development, programming languages, Software testing & others
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:
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:
Additionally, the steps in the Java email program are as follows:
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");
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"));
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.
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();} } }
Output:
Given below are the FAQs mentioned:
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.
Answer: The abstract Multipart class is implemented by the MimeMultipart class, which employs MIME standards for multipart data.
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.
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!