Sunday, January 31, 2016

Sending text email from Java using Apache Commons Email

In this post, I wanted to show how to send an email using Apache Commons Email.

In this post I wanted to cover:
  • The program written in Java to send emails.
  • Challenges that I faced when sending emails.

Things one requires:

  • Eclipse.
  • Java.
  • Apache Commons Email library.
  • Two Gmail accounts (One acts as from address and one as to address) or One Gmail account (From and to address).

Apache Commons Email library can be downloaded from here: Apache Commons Email.

Configuration necessary in Eclipse before writing java program using Apache Commons Email library.

Create a Java project.
Right click on the project and choose properties.
In the properties choose Java Build Path and in Libraries tab click the button Add External Jars button on the right side.

Choose the jar that was downloaded from Apache website and add it.

Click OK and create a new Java class.

My Java class with Apache Commons Email code is as below:

 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
package com.java;

import org.apache.commons.mail.DefaultAuthenticator;
import org.apache.commons.mail.Email;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.SimpleEmail;

public class ApacheMailSample {

 public static void main(String[] args) {
  Email email = new SimpleEmail();
  email.setHostName("smtp.gmail.com");
  email.setSmtpPort(465);
  email.setAuthenticator(new DefaultAuthenticator("<sender>@gmail.com", "<sendersPass>"));
  email.setSSLOnConnect(true);
  email.setStartTLSEnabled(true);
  email.setStartTLSRequired(true);
  try {
   email.setFrom("<sender>@gmail.com");
   email.setSubject("Test email from java program");
   email.addTo("<recipient>@gmail.com");
   email.send();
  } catch (EmailException e) {
   e.printStackTrace();
  }
 }

}

In the above code, I have created an object of class SimpleEmail.

I have set host to smtp.gmail.com, smtp port to 465.

To the DefaultAuthenticator's constructor I have passed Username (from address) and Password.

According to Google, the following has to be configured to send an email.


SMTP HOST: smtp.gmail.com

SMTPPORT: 587 (465 for SSL) 
USE SSL: Optional
SMTP Auth: Login



I have used port 465 in my java program and set SSL to true using method setSSLOnConnect.

I have set TLSEnabled to true using the methods setStartTLSEnabled and setStartTLSRequired.

Using methods setFrom, setSubject, addTo one can add from address, set subject of the email, set to address respectively.

One will have to send email using method send.

Challenges that I have faced:

  • Initially I was getting AuthenticationFailedException, on my google search I found out that we have to enable access to less secure apps on from email address at this link: Less Secure Apps Setting. I had to click turn on to let my java program access the email.
  • I have initially used smtp.googlemail.com and I was getting a message, couldn't connect to smtp host with response -1. After I changed the smtp host to smtp.gmail.com I was able to send emails.
  • Without having methods setStartTLSEnabled and setStartTLSRequired, I was getting the exception AuthenticationFailedException.


After I resolved the above errors, I was able to send email successfully from one email address to another (Gmail).

Sunday, November 29, 2015

Using JQuery to play a GIF on hovering the mouse over.

I used JQuery to implement the hover functionality.

The objective is to play a GIF image when the mouse is on the image and image should go static when the mouse is out of image area.

Once the mouse is out of the image area, the image goes static.

HTML + JQuery code:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
<html>
 <head>
  <script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
  <script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
 </head>
 <body>
  <img src="image_1_static.jpg" id="id1"/>
  <script>
   $(document).ready(function() {
    $("#id1").hover(
     function() {
      $(this).attr("src", "image_1.gif")
     }, function() {
      $(this).attr("src", "image_1_static.jpg")
     }
    );
   });
  </script>
 </body>
</html>


For achieving the above, I took a GIF (image_1.gif), opened the GIF in mspaint and saved it as jpeg/jpg image (image_1_static.jpg), now I have a static image and a GIF.

I took src for the img as the static image (image_1_static.jpg) and in the hover, I have written two functions one that accepts gif (image_1.gif) when mouse hovers over the img area and one that accepts jpeg/jpg (image_1_static.jpg) when mouse is out of img area.

This functionality can be very useful for creating menu icons in a website. When user places mouse over, icon plays.

Suggestions are well appreciated and happy learning.

Friday, November 27, 2015

Stack implementation in Python 3.5

Stack is a data structure that follows the LIFO model last in first out, the data that is inserted last will come out first.

Program for implementation of stack in Python:


 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
stack = []

stackLength = input("Specify the limit of the stack: ")


class Stack:
    def push(self, value):
        if len(stack) != int(stackLength):
            stack.append(value)
            return
        else:
            print("Stack is full !")
            return

    def pop(self):
        if len(stack)!= 0:
            stack.remove(stack[len(stack)-1])
            return
        else:
            print("Stack is empty")
            return

    def length(self):
        return len(stack)

stackClassInst = Stack()
stackClassInst.push(100)
stackClassInst.push(200)
stackClassInst.push(300)
stackClassInst.push(400)
stackClassInst.push(500)
stackClassInst.push(600)
stackClassInst.push(700)
stackClassInst.push(800)
stackClassInst.push(900)
stackClassInst.push(1000)
stackClassInst.push(1100)

print(stack)

lengthofstack = stackClassInst.length();

print(lengthofstack,": is the length of the stack")

stackClassInst.pop();
stackClassInst.pop();
stackClassInst.pop();
stackClassInst.pop();
stackClassInst.pop();
stackClassInst.pop();
stackClassInst.pop();
stackClassInst.pop();
stackClassInst.pop();
stackClassInst.pop();
stackClassInst.pop();

print(stack)

Firstly I took an empty array and I requested the input of stack's length using input.

Once I have input, once push method is called, I compared the length of stack array with the actual length from input.

If the length of the stack reaches the limit, stack is full message is printed.

Otherwise push continues and inserts data into the stack.

In pop, one can remove the elements from stack until it reaches the end of stack, once the end is reached, stack is empty message is printed.

The length method is used to calculate the length of the stack at any given time.

I enclosed push, pop and length methods into a class.

Output:


Specify the limit of the stack: 10
Stack is full !
[100, 200, 300, 400, 500, 600, 700, 800, 900, 1000]
10 : is the length of the stack
Stack is empty
[]

Process finished with exit code 0

Feel free to suggest on the post, happy learning.



Comments

blog comments powered by Disqus