On this article, I will post some code for making simple mail client application with java to sending e-mail via gmail mail server.
Here some coding example that I make :
I use JavaMail API from oracle
http://www.oracle.com/technetwork/java/javamail/index-138643.html
import java.util.Date;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message.RecipientType;
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 SimpleEMailSenderClient {
public static void main(String args[]) {
try {
// Initiate Properties object for configuring the mail client
Properties prop = new Properties();
prop.put("mail.smtp.host", "smtp.gmail.com");
//prop.put("mail.smtp.host", "66.249.93.109");
prop.put("mail.smtp.auth", "true");
prop.put("mail.smtp.port", "465");
prop.put("mail.smtp.socketFactory.port", 465);
prop.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
prop.put("mail.smtp.socketFactory.fallback", "false");
// Create a new javax.mail.Session object
Session session = Session.getDefaultInstance(prop, new Authenticator() {
// Override method to Authanticate to mail server
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("testmail@gmail.com", "testtest");
}
});
// setDebug method fill with Boolean true that will dump trace log of Session Object to console.
session.setDebug(true);
// Initiate MimeMessage for configuring e-mail detail
MimeMessage Msg = new MimeMessage(session);
// setFrom() method is for filling the "From" field in email.
Msg.setFrom(new InternetAddress("testmail@gmail.com"));
// setRecipient() method is for filling the "to, cc, or bcc" in email.
// The first parameter value cab be RecipientType.TO, RecipientType.CC, or Recipient Type.BCC
Msg.setRecipient(RecipientType.TO, new InternetAddress("testing@mymaildomain.com"));
// setSubject() method is for filling the "Subject" field in email.
Msg.setSubject("Message Subject");
// setSentDate() method is to inform the recipient when the mail was sent.
Msg.setSentDate(new Date());
// Initiate MimeBodyPart for filling email content
MimeBodyPart messagePart = new MimeBodyPart();
messagePart.setText("Message Content");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messagePart);
Msg.setContent(multipart);
// Email Sending process
Transport.send(Msg);
// Handle whenever error is occur
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
Hope this post can be helpfull.
Regards,
Erwin Lin