Tags

, , , , , ,


Having tried a couple of mailing techniques.  Common Email from Apache seems to be the simplest so far.

Here below is a sample that you can copy-paste to fire out a mail right away using Google  SMTP server, which

save you from the hassle of configuring your own SMTP server while trying out the package.

All you have to do is to change the to_mailid, from_mailid, your_gmail_username and password accordingly.

import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.SimpleEmail;

/**
*
*/

/**
* @author reisang
*
*/
public class CommonEmail {
public static void main(String[] args)
{
try {
SimpleEmail email = new SimpleEmail();
email.setHostName(“smtp.gmail.com”);
email.addTo(“to_mailid@gmail.com”, “Micky”);
email.setFrom(“from_mailid@gmail.com”, “Me”);
email.setSubject(“Test message”);
email.setMsg(“Body of  the message “);

//gmail requires you to use a valid user account.

email.setAuthentication(“your_gmail_username”,”user_password”);
email.setSSL(true);
email.setTLS(true);
email.send();
} catch (EmailException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}

Here below is another method.

import java.security.Security;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class Mailer
{
private String mailhost = “smtp.gmail.com”;

public synchronized void sendMail(String subject, String body, String sender, String recipients)
throws Exception
{

Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());

Properties props = new Properties();
props.setProperty(“mail.transport.protocol”, “smtp”);
props.setProperty(“mail.host”, mailhost);
props.put(“mail.smtp.auth”, “true”);
props.put(“mail.smtp.port”, “465”);
props.put(“mail.smtp.socketFactory.port”, “465”);
props.put(“mail.smtp.socketFactory.class”,”javax.net.ssl.SSLSocketFactory”);
props.put(“mail.smtp.socketFactory.fallback”, “false”);
props.setProperty(“mail.smtp.quitwait”, “false”);

Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator()
{
protected PasswordAuthentication getPasswordAuthentication()
{ return new PasswordAuthentication(“your gmail account name”,”password”);    }
});

MimeMessage message = new MimeMessage(session);
message.setSender(new InternetAddress(sender));
message.setSubject(subject);
message.setContent(body, “text/plain”);
if (recipients.indexOf(‘,’) > 0)
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients));
else
message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients));

Transport.send(message);

}

public static void main(String args[]) throws Exception
{
Mailer mailutils = new Mailer();
for(int i=0;i<1;i++)
{
mailutils.sendMail(“test”, “This in not a spam”, “sender_email_id”, “recipient_email_id”);
}

}

}

Advertisements