[Tutorial] Send an e-mail with JavaMail and Gmail

On January 19, 2011, in JavaMail, Tutorial, by lucasterdev

Requirements:

- JavaMail jars

- Jaf jars

All these jars must be in the classpath!

Dependencies:

<dependency>
	<groupId>javax.mail</groupId>
	<artifactId>mail</artifactId>
	<scope>provided</scope>
</dependency>

Code:

package my;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.Properties;
import java.util.Date;

import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.Transport;
import javax.mail.URLName;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class Msgsend {

	public static void main(String[] argv) {
		String auth = "true";
		String fallback = "false";
		String debug = "true";

		String port1 = "465";
		String port2 = "25";
		String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";

		//Username and password to connect to the SMTP server
		final String username = "AAAAAA";
		final String password = "BBBBBB";

		//E-mail fields
		String to = "XXXXXX";
		String subject = "This is a JavaMail test.";
		String body = "Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah";
		String from = "YYYYYY";
		String cc = null;
		String bcc = null;
		String url = null;
		String mailhost = "smtp.gmail.com";
		String mailer = "Msgsend";

		// Absolute path to the attached file
		String file = null;

		String protocol = null;
		String host = null;

		String record = null; // name of folder in which to record mail

		try {

			// Initialize the JavaMail Session.
			Properties props = System.getProperties();
			// XXX - could use Session.getTransport() and Transport.connect()
			// XXX - assume we're using SMTP
			props.put("mail.smtp.host", mailhost);
			props.put("mail.smtp.auth", auth);
			props.put("mail.debug", debug);
			props.put("mail.smtp.port", port1);
			props.put("mail.smtp.socketFactory.port", port1);
			props.put("mail.smtp.socketFactory.class", SSL_FACTORY);
			props.put("mail.smtp.socketFactory.fallback", fallback);

			// Get a Session object
			Session session = Session.getDefaultInstance(props,
					new javax.mail.Authenticator() {
						protected PasswordAuthentication getPasswordAuthentication() {
							return new PasswordAuthentication(username,
									password);
						}
					});

			// Construct the message.
			Message msg = new MimeMessage(session);
			msg.setHeader("X-Mailer", mailer);
			msg.setSentDate(new Date());
			if (from != null)
				msg.setFrom(new InternetAddress(from));
			else
				msg.setFrom();
			msg.setRecipients(Message.RecipientType.TO,	InternetAddress.parse(to, false));
			if (cc != null)
				msg.setRecipients(Message.RecipientType.CC,	InternetAddress.parse(cc, false));
			if (bcc != null)
				msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false));
			msg.setSubject(subject);
			if (file != null) {
				// Attach the specified file.
				// We need a multipart message to hold the attachment.
				MimeBodyPart mbp1 = new MimeBodyPart();
				mbp1.setText(body);
				MimeBodyPart mbp2 = new MimeBodyPart();
				mbp2.attachFile(file);
				MimeMultipart mp = new MimeMultipart();
				mp.addBodyPart(mbp1);
				mp.addBodyPart(mbp2);
				msg.setContent(mp);
			} else {
				// If the desired charset is known, you can use
				// setText(body, charset)
				msg.setText(body);
			}

			// Send the message.
			Transport.send(msg);

			System.out.println("\nMail was sent successfully.");

			// Save a copy of the message, if requested.
			if (record != null) {
				// Get a Store object
				Store store = null;
				if (url != null) {
					URLName urln = new URLName(url);
					store = session.getStore(urln);
					store.connect();
				} else {
					if (protocol != null)
						store = session.getStore(protocol);
					else
						store = session.getStore();

					// Connect
					if (host != null || username != null || password != null)
						store.connect(host, username, password);
					else
						store.connect();
				}

				// Get record Folder. Create if it does not exist.
				Folder folder = store.getFolder(record);
				if (folder == null) {
					System.err.println("Can't get record folder.");
					System.exit(1);
				}
				if (!folder.exists())
					folder.create(Folder.HOLDS_MESSAGES);

				Message[] msgs = new Message[1];
				msgs[0] = msg;
				folder.appendMessages(msgs);

				System.out.println("Mail was recorded successfully.");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
 

Leave a Reply