package MailTest; import java.util.Date; import java.util.Properties; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import com.sun.mail.smtp.SMTPTransport; /** * * @author Dan */ public class GoogleMail { private GoogleMail() { } /** * Send email using GMail SMTP server. * * @param username GMail username * @param password GMail password * @param recipientEmail TO recipient * @param title title of the message * @param message message to be sent * @throws AddressException if the email address parse failed * @throws MessagingException if the connection is dead or not in the connected state or if the message is not a MimeMessage */ public static void Send(final String username, final String password, String recipientEmail, String title, String message) throws AddressException, MessagingException { GoogleMail.Send(username, password, recipientEmail, "", title, message); } /** * Send email using GMail SMTP server. * * @param username GMail username * @param password GMail password * @param recipientEmail TO recipient * @param ccEmail CC recipient. Can be empty if there is no CC recipient * @param title title of the message * @param message message to be sent * @throws AddressException if the email address parse failed * @throws MessagingException if the connection is dead or not in the connected state or if the message is not a MimeMessage */ public static void Send(final String username, final String password, String recipientEmail, String ccEmail, String title, String message) throws AddressException, MessagingException { Properties props = System.getProperties(); props.setProperty("smtp.gmail.com", ""); props.setProperty("mail.smtp.port", "465"); props.setProperty("mail.smtps.auth", "true"); Session session = Session.getInstance(props, null); // -- Create a new message -- final MimeMessage msg = new MimeMessage(session); // -- Set the FROM and TO fields -- msg.setFrom(new InternetAddress(username)); msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipientEmail, false)); if (ccEmail.length() > 0) { msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(ccEmail, false)); } msg.setSubject(title); msg.setText(message, "utf-8"); msg.setSentDate(new Date()); SMTPTransport t = (SMTPTransport)session.getTransport("smtps"); t.connect("smtp.gmail.com", username, password); t.sendMessage(msg, msg.getAllRecipients()); t.close(); } }