Thursday, August 22, 2013

Sending mail using Gmail, Live Mail and Yahoo Account

In some of your application, you may have a requirement of sending emails to the user. Like One Time Password, Registration Verification, Unusual Account Activity or may be any other reason.

So, let's check what are needed to achieve the same.

  1. A mail server
  2. A mail sending API
  3. An email account
If you are lucky, you can have the first one set up and you will use that particular server configuration.

Unfortunately you may not be lucky all the time. Many times, you do not have a mail server configured may be due to less usage of mail sending functionality or for cost reason.

Then ?
Hmm, this is really a concern.

To resolve this issue, we can use the standard mail servers we use like GMail, Live Mail, Yahoo Mail etc.

So checkpoint 1 has been achieved.

Let's get into checkpoint 2. For this, we just need to add Java Mail API to our classpath,
If you are using Maven, you have to add this dependency in your pom.xml,


<dependency>
 <groupId>javax.mail</groupId>
 <artifactId>javax.mail-api</artifactId>
 <version>1.5.1</version>
</dependency>
<dependency>
 <groupId>com.sun.mail</groupId>
 <artifactId>javax.mail</artifactId>
 <version>1.5.1</version>
</dependency>

Ivy users have to add the followinig,
<dependency org="javax.mail" name="javax.mail-api" rev="1.5.1"/>

<dependency org="com.sun.mail" name="javax.mail" rev="1.5.1"/>

Or if you are not using any build tool, simply add the JavaMail API Jar

At this point, you are left with the final checkpoint of having a mail account.
If you don't have it, go create one.

Sounds cool !!!

I've a mail account in Live/Gmail/Yahoo. What's next ?

Now that, we have everything we need, let's get our hands dirty with a few lines of code.

Here is the code for sending mails using different mail servers,


 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
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

/**
 * Send mail using Yahoo Account
 * 
 * @author Palash Kanti Kundu
 * @version 1.0
 * @since Aug 21, 2015
 */
public class EmailSender {

 public static void main(String[] args) {
  // Send mail from Yahoo Account
  sendMail("your yahoo account", "********",
    "smtp.mail.yahoo.com", "mail recipient account",
    "Send mail from Java using Yahoo Account",
    "Hi there, This mail has been sent from a Java Program using Yahoo Account");

  // Send mail from Live Account
  sendMail("your live account", "********", "smtp.live.com",
    "mail recipient account",
    "Send mail from Java using Live Account",
    "Hi there, This mail has been sent from a Java Program using Live Account");

  // Send mail from Google Account
  sendMail("your google account", "********",
    "smtp.gmail.com", "mail recipient account",
    "Send mail from Java using Google Account",
    "Hi there, This mail has been sent from a Java Program using Google Account");
 }

 /**
  * Send mail with the parameters
  * 
  * @param userName
  * @param password
  * @param mailServer
  * @param to
  * @param subject
  * @param mailBody
  */
 public static void sendMail(final String userName, final String password,
   String mailServer, String to, String subject, String mailBody) {
  Properties props = new Properties();
  props.put("mail.smtp.auth", "true");
  props.put("mail.smtp.starttls.enable", "true");
  props.put("mail.smtp.host", mailServer);
  props.put("mail.smtp.port", "587");
  Session session = Session.getInstance(props,
    new javax.mail.Authenticator() {
     protected PasswordAuthentication getPasswordAuthentication() {
      return new PasswordAuthentication(userName, password);
     }
    });
  try {
   Message message = new MimeMessage(session);
   message.setFrom(new InternetAddress(userName));
   message.setRecipients(Message.RecipientType.TO,
     InternetAddress.parse(to));
   message.setSubject(subject);
   message.setText(mailBody);
   Transport.send(message);
   System.out.println("Done");
  } catch (MessagingException e) {
   throw new RuntimeException(e);
  }
 }
}

Now run this code once done.

What the hell is this ???


 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
Exception in thread "main" java.lang.RuntimeException: javax.mail.AuthenticationFailedException: 534-5.7.14 <https://accounts.google.com/ContinueSignIn?sarp=1&scc=1&plt=AKgnsbtjg
534-5.7.14 0btmoraJe_6BvT1lraRetqAPP7JrUe6Fv-Ef7PWe-ytmF005ex3J5_3la-92rMAA56cBx5
534-5.7.14 -cef5Ne3y-u-OVmcxqs3e_qMWn27Wyw-9FugRloNKjXVcw6_GuAY79XAgdRcJU9mHBf2cD
534-5.7.14 BLndL4TmzC5yomvYmeuez_jiuNngGjMA3KPTabjpmMSR6iuCyh5SnbtjKulWfBZcazbS-F
534-5.7.14 kDnJp9I3Tpe7XnDnY8YX2CjIkjjY> Please log in via your web browser and
534-5.7.14 then try again.
534-5.7.14  Learn more at
534 5.7.14  https://support.google.com/mail/answer/78754 ea4sm10097329pbc.48 - gsmtp

 at EmailSender.sendMail(EmailSender.java:73)
 at EmailSender.main(EmailSender.java:34)
Caused by: javax.mail.AuthenticationFailedException: 534-5.7.14 <https://accounts.google.com/ContinueSignIn?sarp=1&scc=1&plt=AKgnsbtjg
534-5.7.14 0btmoraJe_6BvT1lraRetqAPP7JrUe6Fv-Ef7PWe-ytmF005ex3J5_3la-92rMAA56cBx5
534-5.7.14 -cef5Ne3y-u-OVmcxqs3e_qMWn27Wyw-9FugRloNKjXVcw6_GuAY79XAgdRcJU9mHBf2cD
534-5.7.14 BLndL4TmzC5yomvYmeuez_jiuNngGjMA3KPTabjpmMSR6iuCyh5SnbtjKulWfBZcazbS-F
534-5.7.14 kDnJp9I3Tpe7XnDnY8YX2CjIkjjY> Please log in via your web browser and
534-5.7.14 then try again.
534-5.7.14  Learn more at
534 5.7.14  https://support.google.com/mail/answer/78754 ea4sm10097329pbc.48 - gsmtp

 at com.sun.mail.smtp.SMTPTransport$Authenticator.authenticate(SMTPTransport.java:843)
 at com.sun.mail.smtp.SMTPTransport.authenticate(SMTPTransport.java:765)
 at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:687)
 at javax.mail.Service.connect(Service.java:367)
 at javax.mail.Service.connect(Service.java:226)
 at javax.mail.Service.connect(Service.java:175)
 at javax.mail.Transport.send0(Transport.java:253)
 at javax.mail.Transport.send(Transport.java:124)
 at EmailSender.sendMail(EmailSender.java:70)
 ... 1 more

I am confused !!!

Oops, you've got the same error, I faced. It is Gmail Authentication error. If you check in your mailbox, you can find that mails were triggered from Live Mail and Yahoo Mail. But Gmail provides some more security to the accounts.

So what, is it impossible to send mail from Gmail ?
Absolutely wrong, you can send mail from GMail too. You just need to tweak some of the security settings in GMail.

So, what do I need to do ?
Follow these steps.
  1. Go to your Account Settings,
  2. Go to Sign In and Security
  3. Scroll down and You will find Allow Less Secure Apps. By default this is set to Off.
  4. Turn this on
Rerun the program and You'll find that everything is working fine.

Hope you enjoyed this post and you are able to send mail without configuring any mail server.

Note: You can find the mails sent from the Java Program in the Sent Item folder when you log in via Web Interface. However, Yahoo mail does not seem to track the mails sent from the Java application. May be I'm doing something wrong or it is a Yahoo feature.

Palash Kanti Kundu Palash Kanti Kundu Palash Kanti Kundu Palash Kanti Kundu Palash Kanti Kundu Palash Kanti Kundu 





Thursday, August 1, 2013

Write your HTML in PDF

Many of the websites are so scool that they allow the content to be downloaded as PDF. You can also make your website that cool. I am using iText for the same. It is available under AGFL. So, if you are making your source code distribution under AGPL or greater public reach than AGPL, then iText should be your choice. Its easy and convenient. Many HTML tags are also supported.

Only external images are not supported and hyperlink did not work for me. Apart from these drawbacks, everything just worked fine. I'll share one input and output from my web page.

Dependencies you need to have,
  • itext-pdfa-5.5.4.jar
  • itext-xtra-5.5.4.jar
  • itextpdf-5.5.4.jar
These dependencies are available here. Choose according to your need.

Program you need to write to create PDF,

 import java.io.File;  
 import java.io.FileNotFoundException;  
 import java.io.FileOutputStream;  
 import java.io.IOException;  
 import java.io.OutputStream;  
 import java.io.StringReader;  
 import com.itextpdf.text.Document;  
 import com.itextpdf.text.DocumentException;  
 import com.itextpdf.text.html.simpleparser.HTMLWorker;  
 import com.itextpdf.text.pdf.PdfWriter;  
 public class PDFCreator {  
      /**  
       *   
       * @param args  
       * @throws DocumentException  
       * @throws IOException  
       */  
      public static void main(String[] args) throws DocumentException,  
                IOException {  
           generatePDF(  
                     "/pdf.pdf",  
                     "<html><head><title>Title</title></head><body><p>Paragraph Tag</p><h1>First Level Header</h1><h2>Second Level Header</h2></body></html>");  
      }  
      /**  
       * Generates HTML with different HTML tags. CSS also supported  
       *   
       * @param filePath  
       * @param htmlData  
       * @throws FileNotFoundException  
       * @throws DocumentException  
       * @throws IOException  
       */  
      public static void generatePDF(String filePath, String htmlData)  
                throws FileNotFoundException, DocumentException, IOException {  
           Document document = new Document();  
           OutputStream output = new FileOutputStream(new File(filePath));  
           PdfWriter.getInstance(document, output);  
           document.open();  
           HTMLWorker htmlWorker = new HTMLWorker(document);  
           htmlWorker.parse(new StringReader(htmlData));  
           document.close();  
           output.close();  
      }  
 }  

That's it. Just use it in your code and you are good to go !!!

Sample from my webpage,

Input text in Editor
This was the input in the web page. Now, I have converted it in a PDF file. The output looks like below,

Output in PDF
That's it. Enjoy writing to PDF from HTML tags !!!
Palash Kanti Kundu