Could not connect to SMTP host) error while sending mail - jakarta-mail

I am facing (Could not connect to SMTP host) error while sending mail by using javax.mail.jar. I am able to send mail through smtp.gmail.com, but when i am trying to connect to my company mail server i am getting the error. I tried from telnet and i am able to send mail from telnet and another python program is also running which is sending mail using the same mail server(ip and port), our bugzilla server is also running on same ip and port and it is successfully sends the mail. I tried to configure the same from java as well as from log4j through SMTP appender but no sucess.
Please guid me.
Thanks In Advance
my code as below -
private Session getSession()
{
Authenticator authenticator = new Authenticator();
Properties properties = new Properties();
properties.setProperty("mail.smtp.submitter", authenticator
.getPasswordAuthentication().getUserName());
properties.setProperty("mail.smtp.auth", "true");
properties.put("mail.smtp.socketFactory.port", "25");
//properties.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
properties.setProperty("mail.smtp.starttls.enable", "true");
properties.setProperty("mail.smtp.host", smtpServer);
properties.setProperty("mail.smtp.port", smtpPort);
return Session.getInstance(properties, authenticator);
}
private class Authenticator extends javax.mail.Authenticator
{
private final javax.mail.PasswordAuthentication authentication;
public Authenticator()
{
authentication =
new javax.mail.PasswordAuthentication(username, password);
}
#Override
protected javax.mail.PasswordAuthentication getPasswordAuthentication()
{
return authentication;
}
}
public boolean sendEmail() throws MessagingException
{
boolean isSuccess = false;
String setBody = "";
String setSubject = "";
try
{
Message message = new MimeMessage(getSession());
setReceipients(message);
message.addFrom(new InternetAddress[]
{ new InternetAddress(emailFrom, "Notification") });
setSubject = emailSubject;
message.setSubject(setSubject);
setBody = emailBody + "\nThis is a System Generated Mail";
message.setContent(setBody, "text/plain");
Transport.send(message);
log.info("Mail Sent Successfully to - " + emailTo);
isSuccess = true;
}
catch (UnsupportedEncodingException ex)
{
log.error("Error in sending Mail without Attachment- "
+ ex.getMessage());
log.warn("Mail Sending Failed for Mail ID:" + emailTo);
}
catch (SendFailedException e)
{
log.error("Invalid Addresses \"" + emailTo + "\" specified:"
+ e.getMessage());
log.warn("Mail Sending Failed for Mail ID:" + emailTo);
}
catch (Exception e)
{
log.error("Error in sending Mail without Attachment- "
+ e.getMessage());
log.warn("Mail Sending Failed for Mail ID:" + emailTo);
}
return isSuccess;
}

The JavaMail FAQ has debugging tips.
It would help to see the debug output from JavaMail.
Possibly you have a firewall or anti-virus program that is blocking port 25.

Related

Unable to capture browser network logs with BrowserStack local, BrowserMobProxy embedded mode and Selenium 3.x using java

Below is the dependencies in my maven pom.xml
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-server</artifactId>
<version>3.14.0</version>
<groupId>net.lightbody.bmp</groupId>
<artifactId>[browsermob-core][1]</artifactId>
<version>2.1.5</version>
<groupId>com.browserstack</groupId>
<artifactId>[browserstack-local-java][1]</artifactId>
<version>1.0.3</version>
Below is the code which I'm using to initiate the BrowserMobProxy.
private static void browserMobSeleniumProxyStart() {
try {
proxy = new BrowserMobProxyServer();
proxy.setTrustAllServers(true);
proxy.chainedProxyAuthorization(
System.getProperty("proxy.user"), System.getProperty("proxy.pass"), AuthType.BASIC);
proxy.setChainedProxy(new InetSocketAddress(httpProxyHost, Integer.parseInt(httpProxyPort)));
// Enable HAR.
proxy.enableHarCaptureTypes(
EnumSet.of(
CaptureType.REQUEST_HEADERS,
CaptureType.REQUEST_CONTENT,
CaptureType.RESPONSE_CONTENT,
CaptureType.RESPONSE_HEADERS
)
);
proxy.start(browserLocalProxyPort);
localHostAddress = Inet4Address.getLocalHost().getHostAddress();
localHostPort = String.valueOf(proxy.getPort());
} catch (Exception e) {
proxy.stop();
e.printStackTrace();
}
Variables httpProxyHost and httpProxyPort are the corporateProxy IP and Port.
Below is the code to initiate the BrowserStack-local
private static void browserStackLocalStart() {
bsLocal = new Local();
bsLocalArgs = new HashMap<>();
bsLocalArgs.put("key", AUTOMATE_ACCESS_KEY);
// BrowserStack local executable.
bsLocalArgs.put("binarypath", format(BROWSERSTACK_PATH, "/src/test/resources/BrowserStackLocal"));
// Force to use local and Corp proxy.
bsLocalArgs.put("forcelocal", "true");
bsLocalArgs.put("forceproxy", "true");
// Set Corp Proxy and user crendentials.
bsLocalArgs.put("proxyHost", httpProxyHost);
bsLocalArgs.put("proxyPort", httpProxyPort);
bsLocalArgs.put("proxyUser", System.getProperty("proxy.user"));
bsLocalArgs.put("proxyPass", System.getProperty("proxy.password"));
// Set local Proxy to BrowserMobProxy host - localhost ip and port and set user credentials.
bsLocalArgs.put("localProxyHost", localHostAddress);
bsLocalArgs.put("localProxyPort", localHostPort);
bsLocalArgs.put("-localProxyUser", System.getProperty("proxy.user"));
bsLocalArgs.put("-localProxyPass", System.getProperty("proxy.password"));
seleniumProxy = ClientUtil.createSeleniumProxy(proxy);
try {
if(bsLocal.isRunning()) bsLocal.stop(bsLocalArgs);
bsLocal.start(bsLocalArgs);
log.info(format("Browser Stack Local status: %s", bsLocal.isRunning()));
} catch (Exception e) {
log.warning("!!! Cannot start browserstack local !!!");
}
}
Below is method to initiate the driver on BrowserStack
private static void setDriverWithBrowserstackOptions() {
// Start BrowserMob proxy and browserstack-local.
browserMobSeleniumProxyStart();
browserStackLocalStart();
String jobName = System.getenv("JOB_BASE_NAME");
DesiredCapabilities caps = new DesiredCapabilities();
caps.setCapability("browserstack.local", "true");
caps.setCapability("browserstack.selenium_version", "3.14.0");
caps.setCapability("browserstack.debug","true");
caps.setCapability("browserstack.networkLogs","false");
caps.setCapability("acceptSslCerts", "true");
caps.setCapability("name", testName);
caps.setCapability("project", "SampleProj");
caps.setCapability("sessionName", "sessionName1");
caps.setCapability("localIdentifier", "Local Test");
caps.setCapability("build", "Local");
caps.setCapability("browserstack.maskCommands", "setValues, getValues, setCookies, getCookies");
caps.setCapability(CapabilityType.PROXY, seleniumProxy);
// Chrome Options.
ChromeOptions options = new ChromeOptions();
options.addArguments("--ignore-certificate-errors");
caps.merge(ChromeOptions.CAPABILITY, options);
URL url = null;
try {
url = new URL(URL);
} catch (MalformedURLException e) {
log.warning("Browserstack URL may be incorrect."+ URL);
}
// Initiate RemoteWebDriver instanc
WebDriver d = new RemoteWebDriver(url, caps);
// Create new HAR.
proxy.newHar();
try {
d.get("https://google.com");
Thread.sleep(10000);
// Fetch Har entries.
List<HarEntry> harEntries = proxy.getHar().getLog().getEntries();
for (HarEntry h : harEntries) {
System.out.println("---------------- HAR Request -----------------");
System.out.println(h.getRequest());
System.out.println("----------------------------------------------");
System.out.println("---------------- HAR Response -----------------");
System.out.println(h.getResponse());
System.out.println("----------------------------------------------");
}
} catch (Exception e) {
e.printStackTrace();
}
}
I tried with and without BrowserMobProxy setChainedProxy but had no luck to capture the HAR entries.
Any thoughts and comments are appreciated.
You just have to set the following capability to capture the network logs on BrowserStack:
caps.setCapability("browserstack.networkLogs","true");
Also, you can capture the contents of the requests made using browserstack.networkLogsOptions. More details on https://www.browserstack.com/automate/capabilities

How to write send email test case and read Excel file test case in Selenium

Here is my my code to write a sample send email test case. When running the code email is not getting triggered. Please find attached data for more details
Login User details
Invalid User Details
Booking Data
Can anyone please help to resolve the issue as I am novice in selenium automation testing. Below is sample code of my Java code for configuration and triggering of email.
How to send out an Email notification in Selenium webdriver using Java, whenever some scenario is failed/passed in between?
public class SendEmail {
public SendEmail() {
}
public void email() {
// Create object of Property file
Properties props = new Properties();
// this will set host of server- you can change based on your
// requirement
props.put("mail.smtp.host", "smtp.gmail.com");
// set the port of socket factory
props.put("mail.smtp.socketFactory.port", "465");
// set socket factory
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
// set the authentication to true
props.put("mail.smtp.auth", "true");
// set the port of SMTP server
props.put("mail.smtp.port", "465");
// This will handle the complete authentication
Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("seleniumtest201#gmail.com", "Admin12!#");
}
});
try {
// Create object of MimeMessage class
Message message = new MimeMessage(session);
// Set the from address
message.setFrom(new InternetAddress("seleniumtest201#gmail.com"));
// Set the recipient address
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("aniketgupta1993#gmail.com"));
// Add the subject link
message.setSubject("Test Case Execution Report");
// Create object to add multi media type content
BodyPart messageBodyPart1 = new MimeBodyPart();
// Set the body of email
messageBodyPart1.setText("This is auto-generated test case execution report");
// Create another object to add another content
MimeBodyPart messageBodyPart2 = new MimeBodyPart();
// Mention the file which you want to send
String filename = "C://Users//aniket//sampleseleniumproject//test-output//emailable-report.html";
// Create data source and pass the filename
DataSource source = new FileDataSource(filename);
// set the handler
messageBodyPart2.setDataHandler(new DataHandler(source));
// set the file
messageBodyPart2.setFileName(filename);
// Create object of MimeMultipart class
Multipart multipart = new MimeMultipart();
// add body part 1
multipart.addBodyPart(messageBodyPart2);
// add body part 2
multipart.addBodyPart(messageBodyPart1);
// set the content
message.setContent(multipart);
// finally send the email
Transport.send(message);
System.out.println("=====Email Sent=====");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
You can use following code for the getting email when execution is completed and this put in teardown so you can get an Email notification in selenium webdriver, whenever scenario is failed/passed in between
public void tearDown()
{
private static void sendPDFReportByGMail(String from, String pass, String to, String subject, String body)
{
Properties props = System.getProperties();
String host = "smtp.gmail.com";
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.user", from);
props.put("mail.smtp.password", pass);
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props);
MimeMessage message = new MimeMessage(session);
try {
//Set from address
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
//Set subject
message.setSubject(subject);
message.setText(body);
BodyPart objMessageBodyPart = new MimeBodyPart();
objMessageBodyPart.setText("Please Find The Attached Report File!");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(objMessageBodyPart);
objMessageBodyPart = new MimeBodyPart();
//Set path to the pdf report file
String filename = System.getProperty("user.dir")+"\\Default test.pdf";
//Create data source to attach the file in mail
DataSource source = new FileDataSource(filename);
objMessageBodyPart.setDataHandler(new DataHandler(source));
objMessageBodyPart.setFileName(filename);
multipart.addBodyPart(objMessageBodyPart);
message.setContent(multipart);
Transport transport = session.getTransport("smtp");
transport.connect(host, from, pass);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
}
catch (AddressException ae) {
ae.printStackTrace();
}
catch (MessagingException me) {
me.printStackTrace();
}
}
}

Error while doing Salesforce Authentication from C# Client Application

Below is the complete code I have written to work with login() for Salesforce authentication. But, I am getting error if I execute the code in .Net client (Console Application). Can anybody please suggest me how to solve this problem.
My onsite coordinator has confirmed that everything is fine as long as Salesforce concerned.
Code
private bool login()
{
string username = "kak.mca#gmail.com";
string password = "Temp0r#ry";
string securityToken = "";
string resultSessionId = string.Empty;
string resultServerUrl = string.Empty;
binding = new SforceService();
binding.Timeout = 60000;
LoginResult lr;
try
{
#region Method1
//lr = binding.login(username, password);
#endregion Method1
#region Method2
using(binding)
{
lr = binding.login(username, password);
resultSessionId = lr.sessionId;
resultServerUrl = lr.serverUrl;
}
#endregion Method2
return true;
}
catch (SoapException e)
{
Console.WriteLine("Fault code: " + e.Code + Environment.NewLine + "Error message: " + e.Message + Environment.NewLine + "Stack trace:" + e.StackTrace);
return false;
}
}
Error:
<font color='red'>Fault code: INVALID_LOGIN<br />
Error message: INVALID_LOGIN: Invalid username, password, security token; or user Locked out.<br />
Stack trace: at System.Web.Services.Protocols.SoapHttpClientProtocol.ReadResponse(SoapClientMessage message, WebResponse response, Stream responseStream, Boolean asyncCall)
at System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters)
at Walkthrough.sforce.SforceService.login(String username, String password) in <filepath>\Web Reference\sforce\Reference.cs:line 545
at Walkthrough.QuickStartApiSample.login() in <filepath>\QuickstartApiSample.cs:line 54
</font>
You are missing security token. You can get one by navigating to your name > Setup > Personal Setup > My Personal Information > Reset My Security Token. Your password variable should be
password = loginPassword + securityToken;
Or you can try Set Up Authorization, Authenticating Apps with OAuth and Digging Deeper into OAuth 2.0 on Force.com
The error was due to improper credentials. When submitted proper credentials, everything went fine.

JavaMail not working properly

Hi When i tried the below code in my home pc it is working fine.
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);
Session sess=Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication("user email ID","password");
}
});
try{
Message msg=new MimeMessage(sess);
msg.setFrom(new InternetAddress("sunnykeerthi#gmail.com"));
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse("sunnykeerthi#gmail.com"));
msg.setSubject("Hi this is mail");
msg.setText("Hi this is an email sent from java");
Transport.send(msg);
JOptionPane.showMessageDialog(null, "message has been sent");
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null, e);
}
but when i tried the same in my office pc it is giving me the error as in the attached screen.
please help.
Is it possible that your company is filtering the port 25?
Can you send a mail from a local desktop client (outlook, thunderbird...) when you set gmail as smtp?
Can you try setting your company smtp server in your java code?

Javamail Configuration clarification

Through my application using Javamail API if I want to send email between any two external email addresses say gmail->yahoo or yahoo->gmail or any other email account without using authentication mechanism how should I configure mail.smtp.host property?
What is the correct way of configuring javamail properties for sending emails between any two external email addresses ?
Sample code to send mail is given below:
Session session = Session.getDefaultInstance(new Properties(),null);
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress("test#gmail.com"));
InternetAddress[] toAddress = {new InternetAddress("test#yahoo.com")};
message.setRecipients(Message.RecipientType.TO, toAddress);
message.setSubject("test mail"); message.setText("test body");
Transport.send(message);
Most public mail servers require authentication. If you want to do it without authentication, you'll need to run your own mail server.
This is for gmail, try it. You need mail.jar
public static void main(String[] args) {
final String username = "yourId#gmail.com";
final String password = "your-pwd";
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("yourId#gmail.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("some-mail#gmail.com"));
message.setSubject("A Mail Subject");
message.setText("Hey I'm sending mail using java api");
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
Edit :
Link to download Java mail Api along with mail.jar

Resources