JavaMail not working properly - jakarta-mail

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?

Related

Add SignalR to Net6 Web Api and connect from Winforms application (.net fx4.8) - hub not found

I'm trying to add signalr to the webapi, I create the CucinaHub class:
public class CucinaHub : Hub
{
static ConcurrentDictionary<string, string> _users = new ConcurrentDictionary<string, string>();
#region Client Methods
public void SetUserName(string userName)
{
_users[Context.ConnectionId] = userName;
}
#endregion Client Methods
}
and configure SignalR:
services.AddSignalR();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapHub<CucinaHub>("/cucinahub");
});
Then in Windows form application I use this code to connect with the hub:
_signalRConnection = new HubConnection($"{Properties.Settings.Default.URL}/api", true);
_hubProxy = _signalRConnection.CreateHubProxy("/cucinahub");
_hubProxy.On("GetValvole", async () => await GetValvole());
try
{
//Connect to the server
await _signalRConnection.Start();
}
catch (Exception ex)
{
Log.Error(ex.ToString());
}
I get always 404 response code:
Hosting environment: Development
Content root path: D:\SwDev\PigsutffHTML\Server\Common\Common.WebApiCore
Now listening on: http://localhost:5000
Application started. Press Ctrl+C to shut down.
info: Microsoft.AspNetCore.Hosting.Diagnostics[1]
Request starting HTTP/1.1 GET http://localhost:5000/api/signalr/negotiate?clientProtocol=2.1&connectionData=[%7B%22Name%22:%22/cucinahub%22%7D] - -
warn: Microsoft.AspNetCore.HttpsPolicy.HttpsRedirectionMiddleware[3]
Failed to determine the https port for redirect.
info: Microsoft.AspNetCore.Hosting.Diagnostics[2]
Request finished HTTP/1.1 GET http://localhost:5000/api/signalr/negotiate?clientProtocol=2.1&connectionData=[%7B%22Name%22:%22/cucinahub%22%7D] - - - 404 0 - 122.4090ms
Where is the error?
Thank you
The key is using the package Microsoft.AspNetCore.SignalR.Client on the WinForm project as client. It is available on .NETFramework. You can see from the picture here:
For testing purpose, I created one webapi project and another winform project. Winform project has been installed the package. Then you can follow the MS document to set up the hubs in webapi project.
Then start the webapi project first to see which port it's running on. Now you can follow the MS Document for setting Clients to set client connect to hub.
For testing purpose, I created two button functions to connect hub and send message to hub, here is the code of connect and send message function button:
private void btnconnect_Click(object sender, EventArgs e)
{
try
{
connection.StartAsync().Wait();
}
catch (Exception ex)
{
//...
}
}
private void btnsend_Click(object sender, EventArgs e)
{
try
{
connection.InvokeAsync("SendMessage",
"winformclient", "hello world").Wait();
}
catch (Exception ex)
{
//...
}
}
And here is the code for setting up client connecting(Remember using your own port here):
HubConnection connection;
public Form1()
{
InitializeComponent();
connection = new HubConnectionBuilder()
.WithUrl("https://localhost:7090/ChatHub")
.Build();
connection.Closed += async (error) =>
{
await Task.Delay(new Random().Next(0, 5) * 1000);
await connection.StartAsync();
};
}
Now start the WinForm Application, click the send button and you can get the result here:
You can see from the screenshot, the hub has already got the message from WinForm application.
Short answer - You cannot mix the .NET 4.x Framework and the .NET Core server/clients. Neither one can talk to the other. You have to upgrade your client. More info in this SO answer.

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();
}
}
}

Could not connect to SMTP host) error while sending 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.

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