In this post, I will share an example on how to send an email with attachment using Java and Google's smtp. You need to use the gmail account's userid and password to authenticate the Google smtp server.
package com.diag.mail;
/**
* import the required libraries
**/
import java.io.File;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
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 SendEmail {
//declare the variables that will be used for the email
private String user,pass,from,subject,message;
String[] recipients;//potentially we have multiple recipients
/**
* a constructor that will initialize the variables
**/
public SendEmail(String user, String pass, String from,
String[] recipients, String subject, String message){
this.user=user;
this.pass=pass;
this.from=from;
this.recipients=recipients;
this.subject=subject;
this.message=message;
}
/**
*use the email details to send the regular email
**/
public void sendEmail(String user, String pass, String from,
String[] recipients, String subject, String message)
throws MessagingException {
// Set the host smtp address
Properties props = new Properties();
//enable the smtp
props.put("mail.smtp.starttls.enable", "true");
//the smtp host is smtp.gmail.com
props.put("mail.smtp.host", "smtp.gmail.com");
//the protocol for email is smtp
props.put("mail.transport.protocol", "smtp");
//enable authorization to send this email
props.put("mail.smtp.auth", "true");
//authenticate to send email, using the username and password
Authenticator auth = new SMTPAuthenticator(user, pass);
//start a new session with the above authentication object
Session session = Session.getDefaultInstance(props, auth);
//we can enable the debug to check the logs in the console
session.setDebug(true);
// create a message
Message msg = new MimeMessage(session);
// set the from and to address
InternetAddress addressFrom = new InternetAddress(from);
msg.setFrom(addressFrom);
InternetAddress[] addressTo = new InternetAddress[recipients.length];
for (int i = 0; i < recipients.length; i++) {
addressTo[i] = new InternetAddress(recipients[i]);
}
msg.setRecipients(Message.RecipientType.TO, addressTo);
// Setting the Subject and Content Type
msg.setSubject(subject);
msg.setContent(message, "text/html");
Transport.send(msg);
System.out.println("***email sent");
}
/**
* send the email with the attachment - this is just an extension of the previous method
**/
public boolean sendLogEmail() throws MessagingException{
Properties props = new Properties();
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.auth", "true");
Authenticator auth = new SMTPAuthenticator(user, pass);
Session session = Session.getDefaultInstance(props, auth);
session.setDebug(true);
String fileAttachment = "path to the attachment";
// Define message
MimeMessage message =
new MimeMessage(session);
InternetAddress addressFrom = new InternetAddress(from);
message.setFrom(addressFrom);
InternetAddress[] addressTo = new InternetAddress[recipients.length];
for (int i = 0; i < recipients.length; i++) {
addressTo[i] = new InternetAddress(recipients[i]);
}
message.setRecipients(Message.RecipientType.TO, addressTo);
message.setSubject(
"Hello JavaMail Attachment");
// create the message part
MimeBodyPart messageBodyPart =
new MimeBodyPart();
//fill message
messageBodyPart.setText("Status Log");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
// Part two is attachment
messageBodyPart = new MimeBodyPart();
File file=new File(fileAttachment);
DataSource source =
new FileDataSource(file);
messageBodyPart.setDataHandler(
new DataHandler(source));
messageBodyPart.setFileName(file.getName());
multipart.addBodyPart(messageBodyPart);
// Put parts in message
message.setContent(multipart);
// Send the message
Transport.send( message );
return true;
}
/**
* SimpleAuthenticator is used to do simple authentication when the SMTP
* server requires it.
*/
private static class SMTPAuthenticator extends javax.mail.Authenticator {
private String username;
private String password;
public SMTPAuthenticator(String username, String password) {
this.username = username;
this.password = password;
}
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
}
/**
* a tester method to test that the whole program is working
* use the correct emails, username and password- the username and password can be one valid gmail-id and its password
**/
public static void main(String args[]){
String recp[]=new String[1];
recp[0]="recipient@gmail.com";
SendEmail sendEmail=new SendEmail("user@gmail.com","password", "fromaddress@mail.com", recp, "Test Email", "");
try {
sendEmail("user@gmail.com","password", "fromaddress@mail.com", recp, "Test Email", "Test Test");
sendEmail.sendLogEmail();
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
package com.diag.mail;
/**
* import the required libraries
**/
import java.io.File;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
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 SendEmail {
//declare the variables that will be used for the email
private String user,pass,from,subject,message;
String[] recipients;//potentially we have multiple recipients
/**
* a constructor that will initialize the variables
**/
public SendEmail(String user, String pass, String from,
String[] recipients, String subject, String message){
this.user=user;
this.pass=pass;
this.from=from;
this.recipients=recipients;
this.subject=subject;
this.message=message;
}
/**
*use the email details to send the regular email
**/
public void sendEmail(String user, String pass, String from,
String[] recipients, String subject, String message)
throws MessagingException {
// Set the host smtp address
Properties props = new Properties();
//enable the smtp
props.put("mail.smtp.starttls.enable", "true");
//the smtp host is smtp.gmail.com
props.put("mail.smtp.host", "smtp.gmail.com");
//the protocol for email is smtp
props.put("mail.transport.protocol", "smtp");
//enable authorization to send this email
props.put("mail.smtp.auth", "true");
//authenticate to send email, using the username and password
Authenticator auth = new SMTPAuthenticator(user, pass);
//start a new session with the above authentication object
Session session = Session.getDefaultInstance(props, auth);
//we can enable the debug to check the logs in the console
session.setDebug(true);
// create a message
Message msg = new MimeMessage(session);
// set the from and to address
InternetAddress addressFrom = new InternetAddress(from);
msg.setFrom(addressFrom);
InternetAddress[] addressTo = new InternetAddress[recipients.length];
for (int i = 0; i < recipients.length; i++) {
addressTo[i] = new InternetAddress(recipients[i]);
}
msg.setRecipients(Message.RecipientType.TO, addressTo);
// Setting the Subject and Content Type
msg.setSubject(subject);
msg.setContent(message, "text/html");
Transport.send(msg);
System.out.println("***email sent");
}
/**
* send the email with the attachment - this is just an extension of the previous method
**/
public boolean sendLogEmail() throws MessagingException{
Properties props = new Properties();
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.auth", "true");
Authenticator auth = new SMTPAuthenticator(user, pass);
Session session = Session.getDefaultInstance(props, auth);
session.setDebug(true);
String fileAttachment = "path to the attachment";
// Define message
MimeMessage message =
new MimeMessage(session);
InternetAddress addressFrom = new InternetAddress(from);
message.setFrom(addressFrom);
InternetAddress[] addressTo = new InternetAddress[recipients.length];
for (int i = 0; i < recipients.length; i++) {
addressTo[i] = new InternetAddress(recipients[i]);
}
message.setRecipients(Message.RecipientType.TO, addressTo);
message.setSubject(
"Hello JavaMail Attachment");
// create the message part
MimeBodyPart messageBodyPart =
new MimeBodyPart();
//fill message
messageBodyPart.setText("Status Log");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
// Part two is attachment
messageBodyPart = new MimeBodyPart();
File file=new File(fileAttachment);
DataSource source =
new FileDataSource(file);
messageBodyPart.setDataHandler(
new DataHandler(source));
messageBodyPart.setFileName(file.getName());
multipart.addBodyPart(messageBodyPart);
// Put parts in message
message.setContent(multipart);
// Send the message
Transport.send( message );
return true;
}
/**
* SimpleAuthenticator is used to do simple authentication when the SMTP
* server requires it.
*/
private static class SMTPAuthenticator extends javax.mail.Authenticator {
private String username;
private String password;
public SMTPAuthenticator(String username, String password) {
this.username = username;
this.password = password;
}
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
}
/**
* a tester method to test that the whole program is working
* use the correct emails, username and password- the username and password can be one valid gmail-id and its password
**/
public static void main(String args[]){
String recp[]=new String[1];
recp[0]="recipient@gmail.com";
SendEmail sendEmail=new SendEmail("user@gmail.com","password", "fromaddress@mail.com", recp, "Test Email", "");
try {
sendEmail("user@gmail.com","password", "fromaddress@mail.com", recp, "Test Email", "Test Test");
sendEmail.sendLogEmail();
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
No comments:
Post a Comment