I've started to build a service monitor using SoapUI 5 (non-Pro edition). The service monitor should be able to:
Teststep1 (http Request): Call an URL, which genereates a token
Teststep2 (groovy script): Parse the response and save the token as a property
Teststep3 (http Request): Call another URL
Teststep4 (groovy script): Parse the repsonseHttpHeader, save the statusHeader in a testCase-property and check if it is '200', '400', '403'...
Teststep5 (groovy script): Write an email whenever it is not '200'
Steps 1 to 4 are working without any problems and also sending emails (step 5) by executing my script is working, but I would like to change the email content depending and the statusHeader. For example:
404: The requested resource could not be found
403 : It is forbidden. Please check the token generator
...
Code for parsing and saving httpHeaderStatusCode:
def groovyUtils = new com.eviware.soapui.support.GroovyUtils( context )
// get responseHeaders of ServiceTestRequest
def httpResponseHeaders = context.testCase.testSteps["FeatureServiceTestRequest"].testRequest.response.responseHeaders
// get httpResonseHeader and status-value
def httpStatus = httpResponseHeaders["#status#"]
// extract value
def httpStatusCode = (httpStatus =~ "[1-5]\\d\\d")[0]
// log httpStatusCode
log.info("HTTP status code: " + httpStatusCode)
// Save logged token-key to next test step or gloabally to testcase
testRunner.testCase.setPropertyValue("httpStatusCode", httpStatusCode)
Code for sending email:
// From http://www.mkyong.com/java/javamail-api-sending-email-via-gmail-smtp-example/
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 SendMailTLS {
public static void main(String[] args) {
final String username = "yourUsername#gmail.com";
final String password = "yourPassword";
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("yourSendFromAddress#domain.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("yourRecipientsAddress#domain.com"));
message.setSubject("Status alert");
message.setText("Hey there,"
+ "\n\n There is something wrong with the service. The httpStatus from the last call was: ");
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
What I want to do: I want to access the testCase httpStatusCode property saved on my first groovy script (last line) in my last groovy script where I send my email. Is there something, which can handle this?
I've searched for two hours, but I have't found something useful. A possible workaround would be that I have to call different Email-Scripts with different messages using if statements and the testRunner.runTestStepByName method, but changing the content of the email would be nicer.
Thanks in advance!
You have to change your class definition in the last groovy script, instead of main define a method to send the email which has statusCode as parameter in your sendMailTLS class. Then in the same groovy script where you define your class use def statusCode = context.expand('${#TestCase#httpStatusCode}'); to get your property value and then create an instance of your class and invoke your method passing the property statusCode with:
// create new instance of your class
def mailSender = new SendMailTLS();
// send the mail passing the status code
mailSender.sendMail(statusCode);
All together in your groovy script have to look like:
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;
// define the class
class SendMailTLS {
// define a method which recive your status code
// instead of define main method
public void sendMail(String statusCode) {
final String username = "yourUsername#gmail.com";
final String password = "yourPassword";
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("yourSendFromAddress#domain.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("yourRecipientsAddress#domain.com"));
message.setSubject("Status alert");
// THERE YOU CAN USE STATUSCODE FOR EXAMPLE...
if(statusCode.equals("403")){
message.setText("Hey there,"
+ "\n\n You recive an 403...");
}else{
message.setText("Hey there,"
+ "\n\n There is something wrong with the service. The httpStatus from the last call was: ");
}
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
// get status code
def statusCode = context.expand('${#TestCase#httpStatusCode}');
// create new instance of your class
def mailSender = new SendMailTLS();
// send the mail passing the status code
mailSender.sendMail(statusCode);
I test this code and it works correctly :).
Hope this helps,
Here is what you can do:
Add a map in your java class which contains all the expected
Response codes, and Response Messages as you wanted to have either
subject or content of email.
I would suggest you to have it in a method other than main so that
you intiantiate class object and call method from soapui's groovy
script, of course you do it with main as well.
Method should take response code as argument.
Use it as key to get the relevant value from the map and put it to
email.
Create a jar file for your class and put jar file under
$SOAPUI_HOME/bin/ext directory
In your soapui test case, for test step5 (groovy) call your method
from the class you wrote like how you call in java. For example: How
to call your java from soapui groovy given below
//use package, and imports also if associated
SendMailTLS mail = new SendMailTLS()
//assuming that you move the code from main method to sendEmail method
mail.sendEmail(context.expand('${#TestCase#httpStatusCode}')
Related
I'm trying to send an email using java.
This is my code.
All my credentials are correct but still I get this error.
I have seen many solutions which says turn on less secure apps but that feature is now disabled by google.
so how do I solve it.
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) {
// Recipient's email ID needs to be mentioned.
String to = "sender#gmail.com";
// Sender's email ID needs to be mentioned
String from = "receiver#gmail.com";
// Assuming you are sending email from through gmails smtp
String host = "smtp.gmail.com";
// Get system properties
Properties properties = System.getProperties();
// Setup mail server
properties.put("mail.smtp.host", host);
properties.put("mail.smtp.port", "465");
properties.put("mail.smtp.ssl.enable", "true");
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
// Get the Session object.// and pass username and password
Session session = Session.getInstance(properties, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("receiver#gmail.com", "password");
}
});
// Used to debug SMTP issues
session.setDebug(true);
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");
System.out.println("sending...");
// Send message
Transport.send(message);
System.out.println("Sent message successfully....");
} catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
This is the error I'm getting.
my error in vs code
Since the less secure app feature is removed we have to follow these below steps to use Gmail via third party software that is App password
Step 1: setup 2-Step Verification:- Google Account -> Security -> 2-Step Verification -> Input password as asked -> Turn ON (you could use SMS to get Gmail code to activate 2-Step Verification)
Step 2: Generate app secret:- Google Account -> Security -> App password -> Input password as asked -> Select the app and device... -> e.g. Other(Java application) -> Input app name e.g. MyApp -> Generate
Step 3: Use generated app secret:- Copy a 16-character password
Use a 16-character password (instead of actual password) with Gmail username in your application
This should save your day
I have looked at many postings on the ( I need to add the mail.jar and activation.jar to oracle Sql developer ):
"javax.mail.NoSuchProviderException:No provider for Address type: rfc822"...
I have written other classes in java that are used by Oracle Forms6i, but can't get this email portion to work. The code that seems to be failing is:
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 EnvoyerEmail {
private String username = "xxxxxxx#gmail.com";
private String password = "****";
public void envoyer() {
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("xxxxx#gmail.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("yyyyyy#gmail.com"));
message.setSubject("Test email");
message.setText("Bonjour, ce message est un test ...");
Transport.send(message);
System.out.println("Message_envoye");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
public static void main(String[] args) {
EnvoyerEmail test = new EnvoyerEmail();
test.envoyer();
}
}
But I keep getting the error mentioned above when it tries to send it. I assure you that I have the mail.jar, activation.jar, pop3.jar, mailapi.jar, smtp.jar, imap.jar in the class path. So that is not the problem.
I was suggested on an Oracle Forum that this will need to be signed. I'm very ignorant of this (the java experience that I have is with JSP), but thought that I got things "secured/signed", but I still keep getting the same problem.
This is the code of the class Mail (there are a main inside but for the simple reason that in this way it seem to be simple to solve this problem):
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
public class Mail {
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 = "mail";
String psw = "password";
// Assuming you are sending email from localhost
String host = "localhost";
// Get system properties
Properties properties = System.getProperties();
// Setup mail server
properties.setProperty("mail.smtps.host", host);
properties.setProperty("mail.user", from);
properties.setProperty("mail.password", psw);
// 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();
}
}
}
And this is the terminal i see after the running:
Exception in thread "main" java.lang.NoClassDefFoundError: javax/activation/DataSource
at Mail.main(Mail.java:35)
Caused by: java.lang.ClassNotFoundException: javax.activation.DataSource
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:582)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:190)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:499)
... 1 more
Process finished with exit code 1
The error is on :
MimeMessage message = new MimeMessage(session);
You either need to tell JDK 9 to expose the included-but-hidden java.activation module, or you need to include the JavaBeans Activation Framework (JAF; javax.activation) jar file in your project explicitly.
Do the former by adding --add-modules java.activation to your java command line.
The latter can be done by using this Maven dependency:
<dependency>
<groupId>com.sun.activation</groupId>
<artifactId>javax.activation</artifactId>
<version>1.2.0</version>
</dependency>
Try the code below
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;
import java.util.Properties;
public class MailTest {
public static void main(String [] args) {
// Recipient's email ID needs to be mentioned.
String to = "tomail";
// Sender's email ID needs to be mentioned
String from = "frommail";
String psw = "password";
// different mail will have different host name, I have implemented using gmail
String host = "smtp.gmail.com";
String port = "587";
Properties props = System.getProperties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", port);
// props.put("mail.smtp.connectiontimeout", timeout);
props.put("mail.smtp.auth", true);
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.starttls.required", "true");
// Get the default Session object.
//Session session = Session.getDefaultInstance(props);
Session session = Session.getInstance(props, new javax.mail.Authenticator()
{
protected PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(from, psw);
}
});
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();
}
}
}
we have an Exchange Server and i wanted to test sending a mail with it. But somehow i always get the error:
com.sun.mail.smtp.SMTPSendFailedException: 550 5.7.1 Message rejected as spam by Content Filtering.
at com.sun.mail.smtp.SMTPTransport.issueSendCommand(SMTPTransport.java:2108)
at com.sun.mail.smtp.SMTPTransport.finishData(SMTPTransport.java:1889)
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1120)
at javax.mail.Transport.send0(Transport.java:195)
at javax.mail.Transport.send(Transport.java:124)
at Test.sendMailJava(Test.java:89)
at Test.main(Test.java:29)
i tried looking at our exchange if anonymous users were allowed and they are, our Printer also send Mails without any authentification.
Here is my Java code, hope someone can help:
import java.net.URI;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import org.simplejavamail.email.Email;
import org.simplejavamail.mailer.Mailer;
import org.simplejavamail.mailer.config.ProxyConfig;
import org.simplejavamail.mailer.config.ServerConfig;
import org.simplejavamail.util.ConfigLoader;
public class Test {
public static void main(String[] args) {
//// // TODO Auto-generated method stub
sendMailJava();
}
public static void sendMailJava()
{
String to = "Recipient"
// Sender's email ID needs to be mentioned
String from = "Sender";
// Assuming you are sending email from localhost
String host = "Server Ip-Adress";
// Get system properties
Properties properties = System.getProperties();
// Setup mail server
properties.setProperty("mail.smtp.host", host);
properties.setProperty("mail.smtp.port", "25");
properties.setProperty("mail.imap.auth.plain.disable","true");
properties.setProperty("mail.debug", "true");
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("Subject");
// Now set the actual message
message.setContent("Content", "text/html; charset=utf-8");
// Send message
Transport.send(message);
System.out.println("Sent message successfully....");
}catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
I also tried SimpleMail, but there is the same error.
The Connection to the smtp Server seems to work, but the message cannot be send, cause of the error above. What could it be?
Greetings,
Kevin
Edit:
i found my error, i don't know why our printers can send maisl without errors but it seems i had to whitelist my ip at our exchange server. Code was completely fine.
thanks for the help
I know you are wanting the smtp option, but I have a feeling the issue is how your server is setup and not in your code. If you get the EWS-Java Api, you can log into your exchange server directly and grab mail that way. Below is the code that would make that work:
public class ExchangeConnection {
private final ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP2); // change to whatever server you are running, though 2010_SP2 is the most recent version the Api supports
public ExchangeConnection(String username, String password) {
try {
service.setCredentials(new WebCredentials(username, password));
service.setUrl(new URI("https://(your webmail address)/ews/exchange.asmx"));
}
catch (Exception e) { e.printStackTrace(); }
}
public boolean sendEmail(String subject, String message, List<String> recipients, List<String> filesNames) {
try {
EmailMessage email = new EmailMessage(service);
email.setSubject(subject);
email.setBody(new MessageBody(message));
for (String fileName : fileNames) email.getAttachments().addFileAttachment(fileName);
for (String recipient : recipients) email.getToRecipients().add(recipient);
email.sendAndSaveCopy();
return true;
}
catch (Exception e) { e.printStackTrace(); return false; }
}
}
In your code you just have to create the class, then use the sendEmail method to send emails to whomever.
Your JavaMail code is not authenticating to your server, which may be why the server is rejecting the message with that error message. (Spammers often use open email servers.)
Change your code to call the Transport.send method that accepts a user name and password.
This piece of code is picked up from http://www.tutorialspoint.com/javamail_api/javamail_api_sending_simple_email.htm
//package com.tutorialspoint;
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) {
// Recipient's email ID needs to be mentioned.
String to = "ABC#gmail.com";
// Sender's email ID needs to be mentioned
String from = "PQR#gmail.com";
final String username = "NAME";
final String password = "****";
// Assuming you are sending email through relay.jangosmtp.net
String host = "relay.jangosmtp.net";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", "25");
// Get the Session object.
Session session = Session.getInstance(props,new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
// Create a default MimeMessage object.
Message message = new MimeMessage(session);
// Set From: header field of the header.
message.setFrom(new InternetAddress(from));
// Set To: header field of the header.
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(to));
// Set Subject: header field
message.setSubject("Testing Subject");
// Now set the actual message
message.setText("Hello, this is sample for to check send "
+ "email using JavaMailAPI ");
// Send message
Transport.send(message);
System.out.println("Sent message successfully....");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
I tried getting hint from this link. But it seems to be using a slightly different method.
On running it with a debugger, exception seems to be coming from following code:
Transport.send(message);
Following is the stack trace:
at com.sun.mail.smtp.SMTPTransport$Authenticator.authenticate(SMTPTransport.java:809)
at com.sun.mail.smtp.SMTPTransport.authenticate(SMTPTransport.java:752)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:669)
at javax.mail.Service.connect(Service.java:317)
at javax.mail.Service.connect(Service.java:176)
at javax.mail.Service.connect(Service.java:125)
at javax.mail.Transport.send0(Transport.java:194)
at javax.mail.Transport.send(Transport.java:124)
at SendEmail.main(SendEmail.java:58)
PS: I have checked the username and password. Also, 2 step sign in process is not enabled for the account from which I am trying to send mail.
Can someone please explain what could be the cause of authenticatio failure? Alternatively, if there is some other post which has already answered the query, please point me to it. Thanks.
The server isn't happy with the username or password you're using. You can probably guess the common reasons that might be the case, staring with you provided the wrong username or password.
The JavaMail Session debugging output might provide more information.
change String host = "relay.jangosmtp.net";
to String host = "smtp.gmail.com";
and Port from 25 to 587