4/10/2012

Use Java Mail to send emails (Gmail)

First download two jar files : mail.jar and activation.jar and add them to the libraries.

Then we can write the code:

01 package javamail;
02 
03 import java.util.Properties;
04 import java.util.Date;
05 import javax.mail.*; // Include Authenticator, Message, PasswordAuthentication, Session, Transport
06 import javax.mail.internet.*; // Include InternetAddress, MimeMessage 
07 import javax.activation.*;
08 
09 public class JavaMailTest {
10     public static void main(String[] args) {
11         final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
12         Properties prop = System.getProperties();
13         prop.setProperty("mail.smtp.host", "smtp.gmail.com");
14         prop.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
15         prop.setProperty("mail.smtp.socketFactory.fallback", "false");
16         prop.setProperty("mail.smtp.port", "465");
17         prop.setProperty("mail.smtp.socketFactory.port", "465");
18         prop.put("mail.smtp.auth", "true");
19         final String user = "XXX@gmail.com";
20         final String password = "XXX";
21         final String filename = "c:\\XXX.doc"// This is the attachment
22         Session session = Session.getDefaultInstance(prop, new Authenticator() {
23             protected PasswordAuthentication getPasswordAuthentication() {
24                 return new PasswordAuthentication(user, password);
25             }
26         });
27         try {
28             Message msg = new MimeMessage(session);
29             msg.setFrom(new InternetAddress("XXX@gmail.com"));
30             msg.setRecipient(Message.RecipientType.TO, new InternetAddress(
31                     "XXX@gmail.com"));
32             msg.setSubject("JavaMail!");
33             msg.setSentDate(new Date());
34 
35             Multipart mp = new MimeMultipart();
36             MimeBodyPart mbpContent = new MimeBodyPart();
37             mbpContent.setText("Send by JavaMail");
38             mp.addBodyPart(mbpContent);
39 
40             MimeBodyPart mbpFile = new MimeBodyPart();
41             FileDataSource fds = new FileDataSource(filename);
42             mbpFile.setDataHandler(new DataHandler(fds));
43             mbpFile.setFileName(fds.getName());
44             mp.addBodyPart(mbpFile);
45 
46             msg.setContent(mp);
47 
48             Transport.send(msg);
49             System.out.println("Message sent successfully!");
50         } catch (Exception e) {
51             System.out.println(e);
52         }
53     }
54 }

No comments:

Post a Comment