Send Mail using java application
YOU CAN SEND EMAIL TO MULTIPLE EMAIL ADDRESSES WITH THIS JAVA PROGRAM.
import java.sql.ResultSet;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Properties;
import java.util.Random;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
/**
*
* @author Krunal Prajapati
*/
public class DownloadBO {
private static final String SMTP_HOST_NAME = "10.61.36.74";
private static final String SMTP_AUTH_USER = "username";
private static final String SMTP_AUTH_PWD = "password";
// private static final String emailMsgTxt = "This mail is sent by a jsp page.so when ever we want to send an E-Mail we can call that Jsp Page only. Thank You.";
private static final String emailSubjectTxt = "Download Request Approved";
private static final String emailFromAddress = "yourname@example.com";
// Add List of Email address to who email needs to be sent to
private static final String[] emailList = {"name1@example.com,
yourname2@example.com"};
public void sendEmailToRequester(Statement stmt, String link, String email, String expiryDate) throws MessagingException {
DownloadBO downloadBO = new DownloadBO();
downloadBO.postMail(email, emailSubjectTxt, link, emailFromAddress,
expiryDate);
System.out.println("Sucessfully Sent mail to All Users");
}
public void postMail(String email, String subject, String message, String
from, String expiryDate) throws MessagingException {
boolean debug = false;
//Set the host smtp address
Properties props = new Properties();
props.put("mail.smtp.host", SMTP_HOST_NAME);
props.put("mail.smtp.auth", "true");
Authenticator auth = new SMTPAuthenticator();
Session session = Session.getDefaultInstance(props, auth);
session.setDebug(debug);
// 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();
addressTo = new InternetAddress(email);
msg.setRecipient(Message.RecipientType.TO, addressTo);
// Setting the Subject and Content Type
msg.setSubject(subject);
msg.setContent("Dear User, \n\n Please write your message body here",
"text/plain");
Transport.send(msg);
}
/**
* SimpleAuthenticator is used to do simple authentication
* when the SMTP server requires it.
*/
private class SMTPAuthenticator extends javax.mail.Authenticator {
public PasswordAuthentication getPasswordAuthentication() {
String username = SMTP_AUTH_USER;
String password = SMTP_AUTH_PWD;
return new PasswordAuthentication(username, password);
}
}
public static void main(String args[]) throws MessagingException {
DownloadBO bO = new DownloadBO();
bO.sendEmailToRequester(emailMsgTxt);
}
}