Hello friends,
In the previous post we have seen How to send email using java (swings) now we will see how to send email with attachment.
Steps.
1. Create a java application
2. Create a java class
3. Download the Mail.Jar and activation.Jar files.
4. Use the following code in to your class file.
Following is the code to send email via java.
send mail using java requires two jar files (i.e Activation.jar, Mail.jar)
Links to download the libraries.
activation.jar
mail.jar
Steps in writing code.
1. Imports to be used.
import java.util.*;
import java.io.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
these are the imports. First two are contained in java package and rest three are in the Javax Package for that u will require mail.jar and activation.jar libraries .
public class AttachExample {
for the purpose of the smtp authentication you require to enter your account username and password and this account will be used to send the mail.
private static final String SMTP_AUTH_USER ="abc";
private static final String SMTP_AUTH_PWD = "pqr123"; // Password
public static void main(String args[]) throws Exception {
Host name of your email service provider if your account is on the gmail then you can use as follows.
String host = "smtp.gmail.com";
this will be your email Id
String from = "abc@gmail.com";
to array stores the list of receipents you can write multiple email ID.
String[] to = {"xxxx@domain.com"};
filename variable contains the name of the file to be attached. It should be a zipped file or any file.
String filename = "AttachFile.txt";
These instance of file is used to get the current directory of your running java application.
File f=new File("..");
System.out.println(f.getAbsolutePath());
Instance of Properties is used to store the System Property.
// Get system properties
Properties props = System.getProperties();
props.put("mail.smtp.starttls.enable","true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.auth", "true");
here you have enabled the authentication.
Authenticator auth = new SMTPAuthenticator();
Created a session
Session session = Session.getDefaultInstance(props, auth);
Created a Instance of message
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
convert the receipents address to the Internet Address
InternetAddress[] toAddress = new InternetAddress[to.length];
for (int i = 0; i < to.length; i++) {
toAddress[i] = new InternetAddress(to[i]);
}
attach all the fields to the message.
message.setRecipients(Message.RecipientType.TO, toAddress);
message.setSubject("Hello JavaMail Attachment");
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText("Here's the file");
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);
message.setContent(multipart);
Send your Email with the attachment.
try {
Transport.send(message);
} catch (SendFailedException sfe) {
message.setRecipients(Message.RecipientType.TO, sfe.getValidUnsentAddresses());
Transport.send(message);
}
}
/**
* SimpleAuthenticator is used to do simple authentication
* when the SMTP server requires it.
*/
private static class SMTPAuthenticator extends javax.mail.Authenticator
{
@Override
public PasswordAuthentication getPasswordAuthentication()
{
String username = SMTP_AUTH_USER;
String password = SMTP_AUTH_PWD;
return new PasswordAuthentication(username, password);
}
}
}
Now the complete code is shown as here
import java.util.*;
import java.io.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
public class AttachExample {
private static final String SMTP_AUTH_USER ="abc";
private static final String SMTP_AUTH_PWD = "pqr123"; // Password
public static void main(String args[]) throws Exception {
String host = "smtp.gmail.com";
String from = "abc@gmail.com";
String[] to = {"xxxx@domain.com"};
String filename = "AttachFile.txt";
File f=new File("..");
System.out.println(f.getAbsolutePath());
//Instance of Properties is used to store the System Property.
// Get system properties
Properties props = System.getProperties();
props.put("mail.smtp.starttls.enable","true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.auth", "true");
Authenticator auth = new SMTPAuthenticator();
Session session = Session.getDefaultInstance(props, auth);
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
convert the receipents address to the Internet Address
InternetAddress[] toAddress = new InternetAddress[to.length];
for (int i = 0; i < to.length; i++) {
toAddress[i] = new InternetAddress(to[i]);
}
message.setRecipients(Message.RecipientType.To,toAddress);
message.setSubject("Hello JavaMail Attachment");
message.setSubject("Hello JavaMail Attachment");
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText("Here's the file");
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);
message.setContent(multipart);
try {
Transport.send(message);
} catch (SendFailedException sfe) {
message.setRecipients(Message.RecipientType.TO, sfe.getValidUnsentAddresses());
Transport.send(message);
}
}
/**
* SimpleAuthenticator is used to do simple authentication
* when the SMTP server requires it.
*/
private static class SMTPAuthenticator extends javax.mail.Authenticator
{
@Override
public PasswordAuthentication getPasswordAuthentication()
{
String username = SMTP_AUTH_USER;
String password = SMTP_AUTH_PWD;
return new PasswordAuthentication(username, password);
}
}
}