This post was most recently updated on August 6th, 2019
Code to automate gamil login, send email and attachment.
To use below code need to replace username password with actual values.
Selenium code to send email using gmail by performing UI Operations. Below code will perform operations like
1) Launch chrome browser
2) Open Gmail URL
3) Enter Email ID and Password
4) Navigate to INBOX
5) Click on Compose email and enter details with attachment
6) Send email.
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 |
package selenium; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; public class Gmail { public static void main(String[] args) throws InterruptedException { System.setProperty("webdriver.chrome.driver", "path of chrome driver"); WebDriver driver = new ChromeDriver(); driver.manage().timeouts().pageLoadTimeout(30, TimeUnit.SECONDS); driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); driver.manage().window().maximize(); driver.get("https://www.gmail.com"); //Send email address driver.findElement(By.xpath("//input[@id='identifierId']")).sendKeys("User mail id"); driver.findElement(By.xpath("//div[@id='identifierNext']")).click(); //send password WebElement passwordButton = driver.findElement(By.xpath("//input[@name='password']")); WebDriverWait wait = new WebDriverWait(driver, 30); wait.until(ExpectedConditions.elementToBeClickable(passwordButton)); passwordButton.sendKeys("Password for Email"); driver.findElement(By.xpath("//div[@id='passwordNext']")).click(); //Click on compose button driver.findElement(By.xpath("//div[text()='Compose']")).click(); //Enter the sender mail id driver.findElement(By.xpath("//textarea[@name='to']")).sendKeys("Sender e-mail id"); //Enter subject to the mail driver.findElement(By.xpath("//input[@name='subjectbox']")).sendKeys("Selenium script"); driver.findElement(By.xpath("//div[@class='Am Al editable LW-avf']")).sendKeys("Selenium script to send mail"); //Attach the full path of file driver.findElement(By.xpath("//input[@name='Filedata']")).sendKeys("D:\\maven.txt"); driver.findElement(By.xpath("//div[text()='Send']")).click(); } } |
To attach a file send the full path of file in input WebElement
Hi Babita,
Thanks for your post… This approach is being blocked by gmail to log into my mailbox. Do you have the gmail reset api request for token generation and refresh the token please?
This does not work anymore. Jan 2020.
good