Without Attachment

	// Setup connection
	Properties props = new Properties();
	props.put("mail.smtps.auth", true);
	//props.put("mail.debug", true); // uncomment to display in console/log

	Session session = Session.getInstance(props);
	//session.setDebug(true); // uncomment to display in console/log

	// Setup message
	Message msg = new MimeMessage(session);
	msg.setFrom(new InternetAddress("your@email.com"));
	msg.setRecipients(Message.RecipientType.TO, new InternetAddress[] { new InternetAddress("their@email.com") });
	msg.setSubject("My Subject");
	msg.setSentDate(new Date());
	msg.setText("my message");

	// Connect and mail
	Transport transport = session.getTransport("smtps");
	transport.connect("smtp.gmail.com", "username", "abc123abc");
	transport.sendMessage(msg, msg.getAllRecipients());
	transport.close();

With Attachment

	// Setup connection
	Properties props = new Properties();
	props.put("mail.smtps.auth", true);
	//props.put("mail.debug", true); // uncomment to display in console/log

	Session session = Session.getInstance(props);
	//session.setDebug(true); // uncomment to display in console/log
	// Setup message

	Message msg = new MimeMessage(session);
	msg.setFrom(new InternetAddress("your@email.com"));
	msg.setRecipients(Message.RecipientType.TO, new InternetAddress[] { new InternetAddress("their@email.com") });
	msg.setSubject("My Subject");
	msg.setSentDate(new Date());

	// Begin attachment
	MimeBodyPart attachment = new MimeBodyPart();

	// Add file to attachment (replace with an existing byte array)
	attachment.setDataHandler(new DataHandler(new ByteArrayDataSource(new byte[]{},
			"text/html")));
	attachment.setFileName("test.html");

	// Create normal email message
	MimeBodyPart text = new MimeBodyPart();
	text.setText("my message");

	// Add attachment and message to email
	Multipart mp = new MimeMultipart();
	mp.addBodyPart(text);
	mp.addBodyPart(attachment);
	msg.setContent(mp);

	// Connect and mail
	Transport transport = session.getTransport("smtps");
	transport.connect("smtp.gmail.com", "username", "abc123abc");
	transport.sendMessage(msg, msg.getAllRecipients());
	transport.close();
Share and Enjoy:
  • Digg
  • E-mail this story to a friend!
  • Reddit
  • del.icio.us
  • Facebook
  • Google
  • StumbleUpon
  • Technorati
  • LinkedIn
  • Slashdot