Archive

Posts Tagged ‘Email’

JavaMail – Send a HTML email with attachment using GMail’s SMTP

June 15th, 2009

After a bundle of trying and testing, here is my final version of send a HTML email with attachment using JavaMail API and GMail’s SMTP Server.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
 
public class Mail {
	public void sendMail() throws Exception {
		String SMTP_SERVER = "smtp.gmail.com";
		String SMTP_PORT = "587";
 
		final String from = "your-email@gmail.com";
		final String password = "your-password";
		String to = "your-friend@somewhere.com";
		String fileAttachment = "/path/to/attachment/file";
 
		String mailSubject = "JavaMail API with Attachment";
		String mailContent = "Hello buddy," +
				"<p>This is an example of sending an HTML email with attachment by JavaMail API.</p>" +
				"<p>Enjoy the code,</p>Your name.";
		String mailFileName = "attachment-name";
 
		// Get system properties
		Properties props = System.getProperties();
 
		// Setup mail server
		props.put("mail.smtp.host", SMTP_SERVER);
		props.put("mail.smtp.port", SMTP_PORT);
		props.put("mail.smtp.starttls.enable","true");
		props.put("mail.smtp.auth", "true");
 
		Authenticator pa = null;
		pa = new Authenticator (){
			public PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication(from, password);
			}
		};
 
		// Get session
		Session session = Session.getInstance(props, pa);
 
		// Define message
		MimeMessage message = new MimeMessage(session);
		message.setFrom(new InternetAddress(from));
		message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
		message.setSubject(mailSubject);
 
		// create the message part 
		MimeBodyPart messageBodyPart = new MimeBodyPart();
 
		//fill message
		messageBodyPart.setContent(mailContent, "text/html");
 
		Multipart multipart = new MimeMultipart();
		multipart.addBodyPart(messageBodyPart);
 
		// Part two is attachment
		messageBodyPart = new MimeBodyPart();
		DataSource source = new FileDataSource(fileAttachment);
		messageBodyPart.setDataHandler(new DataHandler(source));
		messageBodyPart.setFileName(mailFileName);
		multipart.addBodyPart(messageBodyPart);
 
		// Put parts in message
		message.setContent(multipart);
 
		// Send the message
		Transport.send(message);
	}
 
	public static void main(String args[])  {
		try {
			new Mail().sendMail();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

Tested and works like a charm ;)

Coding , , , , , ,