Selenium Email - Old emailable-report.html generated on every test execution - email

Old emailable-report generates after testcase execution in testng.
Here is the code for your reference.
public void EmailFunction() {
try {
EmailAttachment attachment = new EmailAttachment();
attachment.setPath(".\\test-output\\emailable-report.html");
attachment.setDisposition(EmailAttachment.ATTACHMENT);
attachment.setDescription("Test Report Logs");
attachment.setName("Report.html");
// Create the email message
MultiPartEmail email = new MultiPartEmail();
email.setHostName("smtp.gmail.com");
email.setSmtpPort(587);
email.setAuthenticator(new DefaultAuthenticator(MyEmail, MyPassword));
email.setSSLOnConnect(true);
email.setFrom(MyEmail, "Faizan Mamji");
email.addCc("abc#test.com");
email.setSubject("Report Logs");
email.setMsg("Please find attached logs!");
email.addTo(MyEmail, "Faizan Mamji");
// add the attachment
email.attach(attachment);
// send the email
email.send();
}
catch (Exception ex) {
ex.getMessage();
Assert.fail("Email failed to send");
}
}
#AfterTest
public void afterTest() {
TestExecutionEmail ObjEmail= new TestExecutionEmail(maindriver);
maindriver.quit();
ObjEmail.EmailFunction();
}
Please guide how to generate updated report after every complete test execution.

I think you should simply replace the #AfterTest with #AfterSuite annotation as you need to trigger the email code at the very end of the execution.

Related

jmeter send email assertion

I am new to Jmeter and am looking for a way to send emails out for every failed assertion.
Test Structure:
Thread Group:
Transaction Controller:
Http Request:
Http Request:
Http Request:
Thread Group:
Transaction Controller:
Http Request:
Http Request:
Http Request:
Each Http request contains a response assertion. I would like to capture and send one email that contains all of the failed assertions within a transaction controller. Is there a way to do this? I tried using adding a SMTP Sampler within a thread group with a child Bean PreProcessor that contains this code:
import org.apache.jmeter.assertions.AssertionResult;
try {
AssertionResult[] results = prev.getAssertionResults();
StringBuilder body = new StringBuilder();
for (AssertionResult result : results) {
body.append(result.getName());
body.append(result.getFailureMessage());
body.append(System.getProperty("line.separator"));
}
vars.put("body", body.toString());
}
catch (Throwable ex) {
log.error("Error in Beanshell", ex);
throw ex;
}
When i do this it will only send an email of the last failed assertion instead of all failed assertions.
Add a global JSR223 Listener (it is much better to use Groovy rather than Beanshell, see Groovy is the New Black article for details)
Put the following code into "Script" area (it is basically your code but amended to read previous samplers results from the ${body} variable and append new results to them
import org.apache.jmeter.assertions.AssertionResult;
try {
AssertionResult[] results = prev.getAssertionResults();
StringBuilder body = new StringBuilder();
String previousBody = vars.get("body");
if (previousBody != null) {
body.append(previousBody);
}
for (AssertionResult result : results) {
body.append(result.getName());
body.append(result.getFailureMessage());
body.append(System.getProperty("line.separator"));
}
vars.put("body", body.toString());
} catch (Throwable ex) {
log.error("Error in Groovy", ex);
throw ex;
}
We have a test that prints out request body information to the console on failure. This is added to each sampler individually and works quite nicely. You could update this code send a failure message instead of printing to the console.
//Loop through assertions and check for failed
for (int i = 0; i < results.length; i++){
if (results[i].isFailure() || results[i].isError()){
failed_assertion = true;
System.out.println("\n********** Request Body ***************\n"+ctx.getCurrentSampler().getUrl().getPath()+ctx.getCurrentSampler().getQueryString()+'\n'+ctx.getCurrentSampler().getArguments().getArgument(0).getValue()+"\n");
System.out.println("************ ERROR DETECTED ***********\n"+prev.getResponseDataAsString()+"\n****************************************\n");
break;
}
}
If that doesn't work you could construct an IF block on each sampler. Similar to what they're doing here.

I want to send additional parameter with message by Smack API client in ejabberd

I am using Ejabberd as XMPP server and creating xmpp client in smack API.I want to send additional parameter with message.
My code is below :
public static void main(String[] args) throws SmackException,IOException,XMPPException {
XMPPTCPConnectionConfiguration config = XMPPTCPConnectionConfiguration.builder()
.setResource("Smack")
.setSecurityMode(SecurityMode.disabled)
.setServiceName("localhost")
.setHost("localhost")
.setPort(Integer.parseInt("5222"))
.build();
AbstractXMPPConnection conn = new XMPPTCPConnection(config);
try {
conn.setPacketReplyTimeout(10000);
SASLAuthentication.unBlacklistSASLMechanism("PLAIN");
SASLAuthentication.blacklistSASLMechanism("SCRAM-SHA-1");
SASLAuthentication.blacklistSASLMechanism("DIGEST-MD5");
//SASLAuthentication.
conn.connect();
conn.login("test1#localhost","123456");
System.out.println("login successfull");
Message message = new Message();
String stanza = "i am vip";
message.setBody(stanza);
stanza+= "<type>.jpg</type>";
ChatManager manager = ChatManager.getInstanceFor(conn);
manager.createChat("vipul#localhost").sendMessage(message);
message.setBody(stanza);
System.out.println("Message Sent");
} catch (Exception e) {
e.printStackTrace();
}
}
By this code i am able to add type in xmpp stanza but i think it is not preferable way.So i need help to send additional parameter with message.
If i get solution this will be appreciated.
Thanks !!
you can add additional parameter like that-
Message message = new Message();
String stanza = "i am vip";
message.setBody(stanza);
message.addBody("customtag","Custom tag value");
message.addBody("customtag1","Custom tag value1");
and you can get it like-
String customtageValue= message.getBody("customtag");
for more detail check this link

Class MessagingException not working as I think it should

I'm developing a web application that sends an email and has to check, that, in fact this mail has been delivered from my application side as much as possible in few seconds (I don't think you can do more than getting that the email has been delivered to email server, if that email server later cannot later send that email to the user that uses it because it has its inbox full or another situation like this, I think it cannot be helped, although if there's some way I'd like to know about it).
Anyway one thing I think could be checked without problems is if the email address doesn't exist as that gives an inmediate response, according to what I've read this could be done with class MessageException, but I've the following code:
String email=Utils.parseString(req,"email");
[....]
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.starttls.enable","true");
props.put("mail.smtp.EnableSSL.enable","true");
Session s = Session.getInstance(props, null);
MimeMessage message = new MimeMessage(s);
try {
InternetAddress from = new InternetAddress(emailadressthatworks);
message.setFrom(from);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return;
}
try {
InternetAddress to = new InternetAddress(email);
message.addRecipient(Message.RecipientType.TO, to);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
resp.sendRedirect("webpage.jsp");
return;
}
try {
message.setSubject("Subject");
message.setText("message");
Transport.send(message);
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
resp.sendRedirect("webpage.jsp");
return;
}
[....]
And whatever random String I asign to email it never throws an MessagingException in Transport.send(message); so I can redirect it to another jsp web page when I think it should according to what I have read.
Might I be missing something or is it that this class cannot detect that things?
Thanks for your help.
Use the strict InternetAddress constructor and call message.saveChanges() to perform the validation. See
Content-Type syntax check throws exception too late for more details.
See this JavaMail FAQ entry.
Also, it's up to your mail server whether it tries to detect some kinds of errors immediately or whether it queues all requests and only checks for errors later.

JavaMail Get Message for Undelivered Emails (to Gmail or Ymail)

I'm trying to build an app to send bulk report emails to many addresses with various hosts. I'm using Javamail and well, I'm still learning it though.
I found an example and try sending emails with my company server as host (let's say xyz company).
here is the sample code
package mailexample;
import javax.mail.*;
import javax.mail.internet.*;
public class MailExample {
public static void send(String smtpHost, int smtpPort,
String from, String to,
String subject, String content) {
try {
java.util.Properties props = new java.util.Properties();
props.put("mail.smtp.host", smtpHost);
props.put("mail.smtp.port", ""+smtpPort);
Session session = Session.getDefaultInstance(props, null);
//Store store = session.getStore();
//Folder folder = store.getFolder("INBOX");
//System.out.println(folder.getMessage(1));
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(from));
msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
msg.setSubject(subject);
msg.setText(content);
Transport.send(msg);
}
catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception {
try {
send("mail.xyz.ac", 25, "asdf#xyz.ac", "qwer#xyz.ac",
"title", "content");
}
catch(Exception e) {
e.printStackTrace();
}
}
}
It works fine and I get an error stacktrace when the address is invalid.
But that is only happen if I send an email to the same server/host which is mail.xyz.ac.
If I send an email to some random gmail or ymail addresses (that likely don't exist), my app return success message but nothing happened after that, only a message (like mailer-daemon in gmail) in sender inbox that said it is not delivered.
The problem is, I need to store that message in my database for further notice.
Is it possible to get that message from my app?
The JavaMail FAQ is your friend while learning JavaMail. This entry and this entry address your question. Also, be sure to read the entry about common mistakes.

Quartz Scheduler sending email notification multiple time

I am using Quartz for scheduling job. Job is to send reminder email every day at some particular time say 11:00AM. I am able to send reminder mail successfully, but the problem is that it sends more than 1 mails at same time. Sometime it sends 8 mails for 1 reminder request, sometime it sends 5. It seems same job is executed multiple time.
Following is my code,
JobDetail job = JobBuilder.newJob(LmsJob.class)
.withIdentity("lmsJob", org.quartz.Scheduler.DEFAULT_GROUP)
.build();
JobDataMap map = job.getJobDataMap();
map.put("creditMonthlyLeaveBalance", creditMonthlyLeaveBalance);
map.put("dailyUpdationTask", dailyUpdation);
map.put("monthlyPayrollGenerationTask",
monthlyPayrollGenerationTask);
map.put("yearlyMaintenanceOfLeaveBalance",
yearlyMaintenanceOfLeaveBalance);
map.put("emailNotifier", emailNotifier);
try {
CronTrigger trigger = TriggerBuilder
.newTrigger()
.withIdentity("lmsJob", "lmsJobGroup")
.forJob(job)
.startAt(new Date(System.currentTimeMillis()))
.withSchedule(
CronScheduleBuilder
.cronSchedule("00 00 00 ? * *")).build();
scheduler.scheduleJob(job, trigger);
scheduler.start();
// scheduler.shutdown();
} catch (ParseException e) {
e.printStackTrace();
}
Please help me in this, let me know if anything else is needed from my side.
I do not know your entire code,which annotation you gave and stuff.So, I am guessing that you gave annotation like #QuartzEvery("3h"). As far I am guessing, your job is scheduled wrong.To make it run at a particular time of every day,try this...
QuartzManager implements Managed {
.
.
public void start() throws Exception {
.
.
QuartzDailyAt dailyAt = jobType.getAnnotation(QuartzDailyAt.class);
int hours[] = dailyAt.hours();
String hourString =
Arrays.stream(hours).mapToObj(String::valueOf).collect(joining(","));
String cronExpression = String.format("0 0 %s * * ?", hourString);
Trigger trigger = TriggerBuilder.
newTrigger().
startNow().
withSchedule(CronScheduleBuilder.cronSchedule(cronExpression).
inTimeZone(TimeZone.getTimeZone("IST"))).
build();
scheduler.scheduleJob(JobBuilder.newJob(jobType).build(), trigger);
scheduler.start();
.
.
}
.
}
And interface as
#Retention(RetentionPolicy.RUNTIME)
#Target(ElementType.TYPE)
public #interface QuartzDailyAt {
int[] hours();
}
While running your job,add an annotation at the top of the class like
#QuartzDailyAt(hours = {7,8,9,15,16,17})
public class SomeJob extends QuartzJob {.....}
This gives you to run at every particular intervals of a particular time zone...(above it is IST)