Selenium

Reading/Sending email by Selenium

Selenium is one of most widely used popular tool for automation testing. we can use selenium to read email body attachment or to send the email with help of Java Mail Jars.

Sending email through Java with SSL / TLS authentication

The JavaMail API defines classes which represent the components of a mail system. JavaMail does not implement an email server, instead it allows you to access an email server using a Java API. In order to test the code presented, you must have access to an email server. While the JavaMail API specification does not mandate support for specific protocols, JavaMail typically includes support for POP3, IMAP, and SMTP.

Prerequisite:

  • Have access to an SMTP server. You must know the host name, port number, and security settings for your SMTP server. Web mail providers may offer SMTP access, view your email account settings or help to find further information. Be aware that your username is often your full email address and not just the name that comes before the @ symbol.
  • A Java EE IDE and Application Server such as GlassFish or Oracle WebLogic Server. JavaMail can be downloaded as a library in a Java SE application but this tutorial assumes the use of a Java EE application server which would already include JavaMail.

Steps for sending email:

We will cover below 3 scenario to send an email:

1. Send Mail in Java using SMTP without authentication.

2. Send Mail in Java using SMTP with TLS authentication.

3. Send Mail in Java using SMTP with SSL authentication

1.Download java mail jar file which contains the library to send the email.

download-jar-for-email

2.Add jar into your project and if you are working with maven project then you can use dependency.

3. Get the session object – . javax.mail.Session class provides object of session, Session.getDefaultInstance() method and Session.getInstance() method.

    // Setup mail server
    properties.setProperty("mail.smtp.host", host); 

    // mail username and password   
    properties.setProperty("mail.user", "user");                   
    properties.setProperty("mail.password", "password$$");  

Compose the message
javax.mail.Transport class provides method to send the message.

// javax.mail.internet.MimeMessage class is
// mostly used for abstraction. 
MimeMessage message = new MimeMessage(session);

// header field of the header.  
message.setFrom(new InternetAddress(from)); 
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));  
message.setSubject("subject");  
message.setText("Hello, aas is sending email "); 

Send the message –

Transport.send(message);

1.Send Mail in Java using SMTP without authentication full implementation in java

import java.util.*; 
import javax.mail.*; 
import javax.mail.internet.*; 
import javax.activation.*; 

public class SendEmail { 
	
	public static void main(String[] args) 
	{ 
		// change below lines accordingly 
		String to = "got@gmail.com"; 
		String from = "akash@gmail.com"; 
		String host = "localhost"; // or IP address 

		// Get the session object 
		// Get system properties 
		Properties properties = System.getProperties(); 

		// Setup mail server 
		properties.setProperty("mail.smtp.host", host); 

		// Get the default Session object 
		Session session = Session.getDefaultInstance(properties); 

		// compose the message 
		try { 

			// javax.mail.internet.MimeMessage class 
			// is mostly used for abstraction. 
			MimeMessage message = new MimeMessage(session); 

			// header field of the header. 
			message.setFrom(new InternetAddress(from)); 
			message.addRecipient(Message.RecipientType.TO, 
								new InternetAddress(to)); 
			message.setSubject("subject"); 
			message.setText("Hello, aas is sending email "); 

			// Send message 
			Transport.send(message); 
			System.out.println("Yo it has been sent.."); 
		} 
		catch (MessagingException mex) { 
			mex.printStackTrace(); 
		} 
	} 
} 

The program is simple to understand and works well, but in real life most of the SMTP servers use some sort of authentication such as TLS or SSL authentication. So, we will now see how to create Session object for these authentication protocols.

For TLS & SSL you can to know port in which the mail server running those service.

2. Following is the Send Mail in Java using SMTP with TLS authentication full implementation :

import java.util.*; 
import javax.mail.*; 
import javax.mail.internet.*; 
import javax.activation.*; 

public class SendMail { 

	public static void main(String[] args) { 
		
		// change accordingly 
		final String username = "username@gmail.com"; 
		
		// change accordingly 
		final String password = "password"; 
		
		// or IP address 
		final String host = "localhost"; 

		// Get system properties 
		Properties props = new Properties();			 
		
		// enable authentication 
		props.put("mail.smtp.auth", host);			 
		
		// enable STARTTLS 
		props.put("mail.smtp.starttls.enable", "true");	 
		
		// Setup mail server 
		props.put("mail.smtp.host", "smtp.gmail.com");	 
		
		// TLS Port 
		props.put("mail.smtp.port", "587");				 

		// creating Session instance referenced to 
		// Authenticator object to pass in 
		// Session.getInstance argument 
		Session session = Session.getInstance(props, 
		new javax.mail.Authenticator() { 
			
			//override the getPasswordAuthentication method 
			protected PasswordAuthentication 
						getPasswordAuthentication() { 
										
				return new PasswordAuthentication(username, 
												password); 
			} 
		}); 

		try { 
			
			// compose the message 
			// javax.mail.internet.MimeMessage class is 
			// mostly used for abstraction. 
			Message message = new MimeMessage(session);	 
			
			// header field of the header. 
			message.setFrom(new InternetAddress("from-email@gmail.com")); 
			
			message.setRecipients(Message.RecipientType.TO, 
				InternetAddress.parse("to-email@gmail.com")); 
			message.setSubject("hello"); 
			message.setText("Yo it has been sent"); 

			Transport.send(message);		 //send Message 

			System.out.println("Done"); 

		} catch (MessagingException e) { 
			throw new RuntimeException(e); 
		} 
	} 
} 

3. Following is the Send Mail in Java using SMTP with SSL authentication full implementation :

import java.util.*; 
import javax.mail.*; 
import javax.mail.internet.*; 
import javax.activation.*; 

public class SendEmail { 
public static void main(String[] args) 
	{ 
		// change accordingly 
		String to = "got@gmail.com"; 
		
		// change accordingly 
		String from = "akash@gmail.com"; 
		
		// or IP address 
		String host = "localhost"; 
		
		// mail id 
		final String username = "username@gmail.com"
		
		// correct password for gmail id 
		final String password = "mypassword"; 

		System.out.println("TLSEmail Start"); 
		// Get the session object 
		
		// Get system properties 
		Properties properties = System.getProperties(); 
		
		// Setup mail server 
		properties.setProperty("mail.smtp.host", host); 
		
		// SSL Port 
		properties.put("mail.smtp.port", "465"); 
		
		// enable authentication 
		properties.put("mail.smtp.auth", "true"); 
		
		// SSL Factory 
		properties.put("mail.smtp.socketFactory.class", 
				"javax.net.ssl.SSLSocketFactory"); 

		// creating Session instance referenced to 
		// Authenticator object to pass in 
		// Session.getInstance argument 
		Session session = Session.getDefaultInstance(props, 
			new javax.mail.Authenticator() { 
				
				// override the getPasswordAuthentication 
				// method 
				protected PasswordAuthentication 
						getPasswordAuthentication() { 
					return new PasswordAuthentication("username", 
													"password"); 
				} 
			}); 
} 

//compose the message 
try { 
	// javax.mail.internet.MimeMessage class is mostly 
	// used for abstraction. 
	MimeMessage message = new MimeMessage(session); 
	
	// header field of the header. 
	message.setFrom(new InternetAddress(from)); 
	
	message.addRecipient(Message.RecipientType.TO, 
						new InternetAddress(to)); 
	message.setSubject("subject"); 
	message.setText("Hello, aas is sending email "); 

	// Send message 
	Transport.send(message); 
	System.out.println("Yo it has been sent.."); 
} 
catch (MessagingException mex) { 
	mex.printStackTrace(); 
} 
} 
} 

Reading number of emails ,body and attachments:

package qautomation.blog;

import org.testng.annotations.Test;

import javax.mail.*;
import javax.mail.internet.MimeBodyPart;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashSet;
import java.util.Properties;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MailReading {
    Properties properties = null;
    private Session session = null;
    private Store store = null;
    private Folder inbox = null;
    private String userName = "quatomationinfo@gmail.com";// provide user name
    private String password = "Testing@0918";// provide password
    private String saveDirectory = System.getProperty("user.dir") + "\\SaveEmails";


    @Test
    public void main1() {
        MailReading sample = new MailReading();
        sample.readMails();
    }

    public void readMails() {
        properties = new Properties();
        properties.setProperty("mail.store.protocol", "imaps");
        try {
            session = Session.getDefaultInstance(properties, null);
            store = session.getStore("imaps");
            store.connect("imap.gmail.com", userName, password);
            inbox = store.getFolder("INBOX");

            int unreadMailCount = inbox.getUnreadMessageCount();
            System.out.println("No. of Unread Mails = " + unreadMailCount);

            inbox.open(Folder.READ_WRITE);

            Message messages[] = inbox.getMessages();
            System.out.println("No. of Total Mails = " + messages.length);
            for (int i = messages.length; i > (messages.length - unreadMailCount); i--) {
                Message message = messages[i - 1];

                Address[] from = message.getFrom();
                System.out.println("====================================== Mail no.: " + i + " start ======================================");
                System.out.println("Date: " + message.getSentDate());
                System.out.println("From: " + from[0]);
                System.out.println("Subject: " + message.getSubject());

                String contentType = message.getContentType();
                String messageContent = "";

                // store attachment file name, separated by comma
                String attachFiles = "";

                if (contentType.contains("multipart")) {
                    // content may contain attachments
                    Multipart multiPart = (Multipart) message.getContent();
                    int numberOfParts = multiPart.getCount();
                    for (int partCount = 0; partCount < numberOfParts; partCount++) {
                        MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(partCount);
                        if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) {
                            // this part is attachment
                            String fileName = part.getFileName();
                            attachFiles += fileName + ", ";
                            part.saveFile(saveDirectory + File.separator + fileName);
                        } else {
                            // this part may be the message content
                            messageContent = part.getContent().toString();
                        }
                    }

                    if (attachFiles.length() > 1) {
                        attachFiles = attachFiles.substring(0, attachFiles.length() - 2);
                    }
                } else if (contentType.contains("text/plain")
                        || contentType.contains("text/html")) {
                    Object content = message.getContent();
                    if (content != null) {
                        messageContent = content.toString();
                    }
                }
                System.out.println("Attachments: " + attachFiles);
      
                System.out.println("====================================== Mail no.: " + i + " end ======================================");
            }

            // disconnect
            inbox.close(false);
            store.close();
        } catch (NoSuchProviderException ex) {
            System.out.println("No provider for pop3.");
            ex.printStackTrace();
        } catch (MessagingException ex) {
            System.out.println("Could not connect to the message store");
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }

    }  
}

References:

https://www.seleniummaster.com/sitecontent/index.php/java-tutorial/java-email/315-sending-email-with-attachments-in-java

http://www.helloselenium.com/2014/10/how-to-send-email-using-java-mail-from.html

Categories: Selenium

2 replies »

Leave a Reply