I have a Gradle project in my Eclipse IDE and I need to be able to send an e-mail receipt as part of a school project. I looked at this link http://www.tutorialspoint.com/java/java_sending_email.htm to try and create the most basic e-mail. I've tried the "sending a simple e-mail" example and I got this as my error:
Usage - java org.mortbay.jetty.Main [<addr>:]<port>
Usage - java org.mortbay.jetty.Main [<addr>:]<port> docroot
Usage - java org.mortbay.jetty.Main [<addr>:]<port> -webapp myapp.war
Usage - java org.mortbay.jetty.Main [<addr>:]<port> -webapps webapps
Usage - java -jar jetty-x.x.x-standalone.jar [<addr>:]<port>
Usage - java -jar jetty-x.x.x-standalone.jar [<addr>:]<port> docroot
Usage - java -jar jetty-x.x.x-standalone.jar [<addr>:]<port> -webapp myapp.war
Usage - java -jar jetty-x.x.x-standalone.jar [<addr>:]<port> -webapps webapps
I'm guessing I don't have the JavaMail API and Java Activation Framework (JAF) properly installed. I've followed some guides on how to do that. What I've done was right click gradle project -> Properties -> Java Build Path -> Libraries tab -> Add External JARs.. And I added the JAF and JavaMail jar files (activation-1.1.1.jar and mail-1.4.5.jar). I also added
compile group: 'javax.mail', name: 'mail', version: '1.4.5'
compile group: 'javax.activation', name: 'activation', version: '1.1.1'
to my build.gradle file. Any help on how to get this working would be greatly appreciated.
Here is the code I used.
// File Name SendEmail.java
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
public class SendEmail
{
public static void main(String [] args)
{
// Recipient's email ID needs to be mentioned.
String to = "abcd#gmail.com";
// Sender's email ID needs to be mentioned
String from = "web#gmail.com";
// Assuming you are sending email from localhost
String host = "localhost";
// 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);
try{
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(session);
// Set From: header field of the header.
message.setFrom(new InternetAddress(from));
// Set To: header field of the header.
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
// Set Subject: header field
message.setSubject("This is the Subject Line!");
// Now set the actual message
message.setText("This is actual message");
// Send message
Transport.send(message);
System.out.println("Sent message successfully....");
}catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
You have to give proper settings to send email. like
String host = "localhost"; // instead of localhost you have to give your hostname.
If you want to send mail via gmail, use the following code:
SendEmail.java
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;
public class SendEmail{
public static void main(String[] args) {
final String username = "username#gmail.com";
final String password = "password";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
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("from-email#gmail.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("to-email#gmail.com"));
message.setSubject("Testing Subject");
message.setText("Welcome Message");
Transport.send(message);
System.out.println("Mail Sent Successfully");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
Related
I have tried to use apache common mail API. the code i used is
public static void main(String[] args) throws EmailException {
System.out.print("-------Start------");
// TODO Auto-generated method stub
Email email = new SimpleEmail();
email.setHostName("smtp.googlemail.com");
email.setSmtpPort(465);
email.setAuthenticator(new DefaultAuthenticator(userName, password));
email.setSSLOnConnect(true);
email.setFrom("user#gmail.com");
email.setSubject("TestMail");
email.setMsg("This is a test mail ... :-)");
email.addTo("myemail#gmail.com");
email.send();
System.out.print("-------End------");
}
but It is saying username and password not accepted however i am providing the correct credentials. When i opened my gmail account , it is showing that it has blocked the sign in attempt. Is there any other way to achieve this?
Please download https://github.com/javaee/javamail/releases
And follow the example below on how to setup Gmail using JavaMail. You dont need any webdriver for this. The javamail jar in your classpath is sufficient.
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
public class SendEmailTLS {
public static void main(String[] args) {
final String username = "username#gmail.com";
final String password = "password";
Properties prop = new Properties();
prop.put("mail.smtp.host", "smtp.gmail.com");
prop.put("mail.smtp.port", "587");
prop.put("mail.smtp.auth", "true");
prop.put("mail.smtp.starttls.enable", "true"); //TLS
Session session = Session.getInstance(prop,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("from#gmail.com"));
message.setRecipients(
Message.RecipientType.TO,
InternetAddress.parse("to_username_a#gmail.com, to_username_b#yahoo.com")
);
message.setSubject("Testing Gmail TLS");
message.setText("Dear Mail Crawler,"
+ "\n\n Please do not spam my email!");
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
If still having trouble, you might need to use and trust an APP Password.
https://support.google.com/accounts/answer/185833?p=InvalidSecondFactor
Create & use App Passwords
If you use 2-Step-Verification and get a "password incorrect" error when you sign in, you can try to use an App Password.
Go to your Google Account.
Select Security.
Under "Signing in to Google," select App Passwords. You may need to sign in. If you don’t have this option, it might be because:
2-Step Verification is not set up for your account.
2-Step Verification is only set up for security keys.
Your account is through work, school, or other organization.
You turned on Advanced Protection.
At the bottom, choose Select app and choose the app you using and then Select device and choose the device you’re using and then Generate.
Follow the instructions to enter the App Password. The App Password is the 16-character code in the yellow bar on your device.
Tap Done.
Tip: Most of the time, you’ll only have to enter an App Password once per app or device, so don’t worry about memorizing it.
Reference: https://mkyong.com/java/javamail-api-sending-email-via-gmail-smtp-example/
So I Made A Java Mailing Bot Using javax.mail(Gradle)
After Hours Of Debugging I Got The Dependency To Work
But I Get This Error Now
I Am Using JDK 11
IntelliJ Idea Ultimate 2020.2.3
> Process 'command 'C:/Program Files/Java/jdk-11.0.8/bin/java.exe'' finished with non-zero exit value 1
This Does Not Allow Me To Run Main.Main()
Here Is The Code -
build.gradle
id 'java'
}
group 'com.putopug.mailerdeamon'
version 'DAEMON'
repositories {
mavenCentral()
}
dependencies {
testCompile group: 'junit', name: 'junit', version: '4.12'
//compile group: 'javax.mail', name: 'javax.mail-api', version: '1.6.2'
//compile 'javax.mail:javax.mail-api:1.6.2'
compile group: 'javax.mail', name: 'mail', version: '1.5.0-b01'
}
Main.java
import javax.mail.*;
import javax.mail.internet.*;
import java.io.Console;
import java.util.Properties;
public class Main {
public static void main(String[] args) throws MessagingException {
Properties prop = new Properties();
prop.put("mail.smtp.auth", true);
prop.put("mail.smtp.starttls.enable", "true");
prop.put("mail.smtp.host", "smtp.gmail.com");
prop.put("mail.smtp.port", "465");
prop.put("mail.smtp.ssl.trust", "smtp.gmail.com");
Session session = Session.getInstance(prop, new Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("gemail", "ddddddd");
}
});
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("email"));
message.setRecipients(
Message.RecipientType.TO, InternetAddress.parse("email"));
message.setSubject("Mail Subject");
String msg = "This is my first email using JavaMailer";
MimeBodyPart mimeBodyPart = new MimeBodyPart();
mimeBodyPart.setContent(msg, "text/html");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(mimeBodyPart);
message.setContent(multipart);
Transport.send(message);
}
}
I Just Had To Surround The Code With A Try Catch loop
There are few articles out there about this, but non of them worked for me. Basically I have following java code to connect to office 365:
Properties props = new Properties();
props.put("mail.imaps.auth.plain.disable", "true");
props.put("mail.imaps.ssl.enable", "true");
session = Session.getInstance(props, null);
store = session.getStore("imaps");
store.connect("outlook.office365.com", 993, "user#mydomain.com", "psw");
but it fails with LOGIN failed error;
javax.mail.AuthenticationFailedException: LOGIN failed.
at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:725)
at javax.mail.Service.connect(Service.java:366)
Also I'm able to login into my account using IMAPS from Thunderbird.
Any pointers to resolve an issue would be appreciated!
This code works for me for outlook I have modified it for use with Office365. I did the research to find the IMAP host for office 365. I hope it helps you.
public static void main(String[] args) throws MessagingException {
MultiPartEmail email = new MultiPartEmail();
Properties props = new Properties();
props.setProperty("mail.store.protocol", "imaps");
//extra codes required for reading OUTLOOK mails during IMAP-start
props.setProperty("mail.imaps.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.setProperty("mail.imaps.socketFactory.fallback", "false");
props.setProperty("mail.imaps.port", "993");
props.setProperty("mail.imaps.socketFactory.port", "993");
//extra codes required for reading OUTLOOK mails during IMAP-end
Session session = Session.getDefaultInstance(props, null);
Store store = session.getStore("imaps");
store.connect("outlook.office365.com", "some.one#some.org", "mypassword");
Folder inbox = store.getFolder("INBOX");
inbox.open(Folder.READ_WRITE);
inbox.addMessageCountListener(new MessageCountListener() {
#Override
public void messagesAdded(MessageCountEvent messageCountEvent) {
Message[] messages = messageCountEvent.getMessages();
System.out.println("A message was added, you now have: " + messages.length + " emails");
}
#Override
public void messagesRemoved(MessageCountEvent messageCountEvent) {
}
});
while (true) {
try {
Thread.sleep(1500);
} catch (InterruptedException e) {
e.printStackTrace();
}
inbox.getMessageCount(); // Keeps connection alive
}
}
As it turned out, office 365 was rejecting connections because of unsupported characters inside the password. Particularly quote character. So, as simple as changing psw fixed my problem.
And following code snippet works just fine:
Properties props = new Properties();
props.put("mail.store.protocol", "imaps");
session = Session.getInstance(props, null);
store = session.getStore();
store.connect("outlook.office365.com", 993, "user#mydomain.com", "psw");
With 'javax.mail', version: '1.5.6'
I'm trying to send emails through JavaMail API but I end up receiving the SocketException: Connection reset.
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
public class SendMailSSL {
public static void main(String[] args) {
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
Authenticator auth = new Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("userName#gmail.com","gmailPassword");
}
};
Session session = Session.getDefaultInstance(props,auth);
try {
Message message = new MimeMessage(session);
Address sender = new InternetAddress("any#...");
message.setFrom(sender);
String recipients = "email1#...,email2#...,email2#...";
String[] toList = recipients.split(",");
System.out.println(toList.length);
Address[] addressTo = new InternetAddress[toList.length];
for(int i = 0; i < toList.length; i++){
addressTo[i] = new InternetAddress(toList[i]);
}
for( int i=0; i < addressTo.length; i++) { // changed from a while loop
message.addRecipient(Message.RecipientType.TO, addressTo[i]);
}
message.setSubject("Testing Subject 5");
message.setText("Dear Message ," +
"\n\n HELLO, please! \n https://192.168.192.120:8181/centralWeb");
System.out.println("SENDING MAIL......... " + new Date().toString());
message.setHeader("Content-type", "text/html; charset=UTF-8");
Transport.send(message);
System.out.println("Done " + new Date().toString());
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
NetBeans Output:
1
SENDING MAIL......... Sun Apr 28 01:30:18 IST 2013
Exception in thread "main" java.lang.RuntimeException: javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465;
nested exception is:
java.net.SocketException: Connection reset
at sendmailssl.SendMailSSL.main(SendMailSSL.java:65)
Caused by: javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465;
nested exception is:
java.net.SocketException: Connection reset
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1706)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:525)
at javax.mail.Service.connect(Service.java:313)
at javax.mail.Service.connect(Service.java:172)
at javax.mail.Service.connect(Service.java:121)
at javax.mail.Transport.send0(Transport.java:190)
at javax.mail.Transport.send(Transport.java:120)
at sendmailssl.SendMailSSL.main(SendMailSSL.java:60)
Caused by: java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(SocketInputStream.java:189)
at java.net.SocketInputStream.read(SocketInputStream.java:121)
at sun.security.ssl.InputRecord.readFully(InputRecord.java:312)
at sun.security.ssl.InputRecord.read(InputRecord.java:350)
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:927)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1328)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1355)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1339)
at com.sun.mail.util.SocketFetcher.configureSSLSocket(SocketFetcher.java:503)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:234)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1672)
... 7 more
Java Result: 1
BUILD SUCCESSFUL (total time: 2 seconds)
I've tried disabling IPv6 and turning off my firewall too, but the problem persists. I am using Windows 7 x64, if that matters.
Thanks to anyone who can help me fix this issue.
Try these debugging tips from the JavaMail FAQ:
How do I debug my application that uses JavaMail APIs?
How do I debug problems connecting to my mail server?
Also, you might want to correct these common mistakes, although I don't think they're related to your problem.
I tried to automate sending email from Gmail (https://accounts.google.com/ServiceLogin?service=mail&passive=true&rm=false&continue=http://mail.google.com/mail/&scc=1<mpl=default<mplcache=2) by using Selenium WebDriver with Java. First I tried to record the test by using Selenium IDE. IDE failed to record the body of email.
I tried by the following way to type on body text, but it failed unfortunately.
driver.findElement(By.xpath("//textarea[#name='body']")).sendKeys("body text");
Error is: FAILED: testSendingEmail
org.openqa.selenium.ElementNotVisibleException: Element is not currently visible and so may not be interacted with Command duration or timeout: 30.02 seconds
Can anybody please help me?
YES.. you can't record the body of email using Selenium IDE.
include the following method in your project and call that method to send Email.(No need to login into gmail)
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
public void SendEmail()
{
// Recipient's email ID needs to be mentioned.
String to = "abcd#gmail.com";
// Sender's email ID needs to be mentioned
String from = "web#gmail.com";
// Assuming you are sending email from localhost
String host = "localhost";
// 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);
try{
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(session);
// Set From: header field of the header.
message.setFrom(new InternetAddress(from));
// Set To: header field of the header.
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
// Set Subject: header field
message.setSubject("This is the Subject Line!");
// Now set the actual message
message.setText("This is actual message");
// Send message
Transport.send(message);
//System.out.println("Sent message successfully....");
}
catch (MessagingException mex) {
mex.printStackTrace();
}
}
You can also send mail with Attachments
Refer this link for more information.
when using class it throws and error element not found its better to use table index.
WebElement frame1 = driver.findElement(By.xpath("//iframe[#tabindex='1']"));
driver.switchTo().frame(frame1);
WebElement editable = driver.switchTo().activeElement();
String mailBody = "Hi," + '\n' + "Gmail Body";
editable.sendKeys(mailBody);
driver.switchTo().defaultContent();
The following is the piece of HTML code for typing gmail body:
<iframe frameborder="0" style="padding: 0pt; height: 218px; background-color: white;" class="Am Al editable" id=":4z" tabindex="1"></iframe>
I have written the following java code in WebDriver to type gmail body and it worked nicely. (I am happy)
WebDriver driver = new FirefoxDriver();
WebElement frame1 = driver.findElement(By.xpath("//iframe[#class='Am Al editable']"));
driver.switchTo().frame(frame1);
WebElement editable = driver.switchTo().activeElement();
String mailBody = "Hi," + '\n' + "I'm Ripon from Dhaka, Bangladesh.";
editable.sendKeys(mailBody);
driver.switchTo().defaultContent();
Try out below code to write in body area
driver.findElement(By.cssSelector("body[class='editable LW-avf']")).clear();
driver.findElement(By.cssSelector("body[class='editable LW-avf']")).sendKeys("body text");
WebDriver driver= new FirefoxDriver();
WebElement text=driver.findElement(By.className("LW-avf"));
text.click();
text.sendKeys("Hello");
Please try using above code.