Jmeter Groovy JavaMail API multipart add content to sample result - email

Looking at answers posted in Reading Emails based on recipient email id in Jmeter using groovy I actually managed to use the recipient search term.
Using the below in a JSR223 Sampler
import javax.mail.Multipart
import javax.mail.internet.MimeMultipart
import javax.mail.Message
import javax.mail.search.RecipientStringTerm
Properties properties = new Properties()
properties.put('mail.imap.host', 'your mail server host') // i.e. imap.gmail.com
properties.put('mail.imap.port', your mail server port) // i.e. 993
properties.setProperty('mail.imap.socketFactory.class', 'javax.net.ssl.SSLSocketFactory')
properties.setProperty('mail.imap.socketFactory.fallback', 'false')
properties.setProperty('mail.imap.socketFactory.port', 'your_mail_server_port') // i.e. 993
def session = javax.mail.Session.getDefaultInstance(properties)
def store = session.getStore('imap')
store.connect('your username (usually email address)', 'your_password')
def inbox = store.getFolder('INBOX')
inbox.open(javax.mail.Folder.READ_ONLY)
def onlyToGivenUser = inbox.search(new RecipientStringTerm(Message.RecipientType.TO,'your_recipient_address')) // i.e. test+1#gmail.com
onlyFromGivenUser.each { message ->
if (message.getContent() instanceof Multipart) {
StringBuilder content = new StringBuilder()
def multipart = (Multipart) message.getContent()
multipart.eachWithIndex { Multipart entry, int i ->
def part = entry.getBodyPart(i)
if (part.isMimeType('text/plain')) {
content.append(part.getContent().toString())
}
}
SampleResult.setResponseData(content.toString(), 'UTF-8')
} else {
SampleResult.setResponseData(message.getContent().toString(), 'UTF-8')
}
}
This works perfectly, but fails when email is ContentType: multipart/MIXED as it does not drill down to multipart/RELATED, multipart/ALTERNATIVE and then to TEXT/PLAIN or TEXT/HTML, on which I like to do a regex on to extract a link from the body.
Guessing some counter on i is needed and an "if else", or something like mentioned here, but unsure how to convert to fit in the above script...
Any help would be much appreciated.

I stepped away from javax.mail.Multipart and javax.mail.internet.MimeMultipart and have implemented the below code in a While Controller
import javax.mail.Message
import javax.mail.search.RecipientStringTerm
Properties properties = new Properties();
properties.put('mail.imap.host', 'your mail server host') // i.e. imap.gmail.com
properties.put('mail.imap.port', your mail server port) // i.e. 993
properties.setProperty('mail.imap.socketFactory.class', 'javax.net.ssl.SSLSocketFactory')
properties.setProperty('mail.imap.socketFactory.fallback', 'false')
properties.setProperty('mail.imap.socketFactory.port', 'your_mail_server_port') // i.e. 993
def session = javax.mail.Session.getDefaultInstance(properties)
def store = session.getStore('imap')
store.connect('your username (usually email address)', 'your_password')
def inbox = store.getFolder('INBOX');
inbox.open(javax.mail.Folder.READ_ONLY);
def onlyToGivenUser = inbox.search(new RecipientStringTerm(Message.RecipientType.TO,'your_recipient_address')); // i.e. test+1#gmail.com
try {
onlyToGivenUser.each { message ->
ByteArrayOutputStream emailRaw = new ByteArrayOutputStream();
message.writeTo(emailRaw);
SampleResult.setResponseData(emailRaw.toString(), 'UTF-8');
}
} catch (Exception ex) {
log.warn("Something went wrong", ex);
throw ex;
}
Hope this helps someone one day.

Related

Groovy script for Jenkins: execute HTTP request without 3rd party libraries

I need to create a Groovy post build script in Jenkins and I need to make a request without using any 3rd party libraries as those can't be referenced from Jenkins.
I tried something like this:
def connection = new URL( "https://query.yahooapis.com/v1/public/yql?q=" +
URLEncoder.encode(
"select wind from weather.forecast where woeid in " + "(select woeid from geo.places(1) where text='chicago, il')",
'UTF-8' ) )
.openConnection() as HttpURLConnection
// set some headers
connection.setRequestProperty( 'User-Agent', 'groovy-2.4.4' )
connection.setRequestProperty( 'Accept', 'application/json' )
// get the response code - automatically sends the request
println connection.responseCode + ": " + connection.inputStream.text
but I also need to pass a JSON in the POST request and I'm not sure how I can do that. Any suggestion appreciated.
Executing POST request is pretty similar to a GET one, for example:
import groovy.json.JsonSlurper
// POST example
try {
def body = '{"id": 120}'
def http = new URL("http://localhost:8080/your/target/url").openConnection() as HttpURLConnection
http.setRequestMethod('POST')
http.setDoOutput(true)
http.setRequestProperty("Accept", 'application/json')
http.setRequestProperty("Content-Type", 'application/json')
http.outputStream.write(body.getBytes("UTF-8"))
http.connect()
def response = [:]
if (http.responseCode == 200) {
response = new JsonSlurper().parseText(http.inputStream.getText('UTF-8'))
} else {
response = new JsonSlurper().parseText(http.errorStream.getText('UTF-8'))
}
println "response: ${response}"
} catch (Exception e) {
// handle exception, e.g. Host unreachable, timeout etc.
}
There are two main differences comparing to GET request example:
You have to set HTTP method to POST
http.setRequestMethod('POST')
You write your POST body to outputStream:
http.outputStream.write(body.getBytes("UTF-8"))
where body might be a JSON represented as string:
def body = '{"id": 120}'
Eventually it's good practice to check what HTTP status code returned: in case of e.g. HTTP 200 OK you will get your response from inputStream while in case of any error like 404, 500 etc. you will get your error response body from errorStream.

Sending an email from scala - Authentication failed exception

I am trying to send an email(gmail) from scala. Here is what I have so far-
import javax.mail._
import javax.mail.internet._
// Get the user's message
var bodyText = "Hello World!"
// Set up the mail object
val props = System.getProperties
props.setProperty("mail.smtp.host", "smtp.gmail.com")
props.setProperty("mail.smtp.user","user");
props.setProperty("mail.smtp.host", "smtp.gmail.com");
props.setProperty("mail.smtp.port", "587");
props.setProperty("mail.debug", "true");
props.setProperty("mail.smtp.auth", "true");
props.setProperty("mail.smtp.starttls.enable","true");
props.setProperty("mail.smtp.EnableSSL.enable","true");
val session = Session.getInstance(props)
val message = new MimeMessage(session)
// Set the from, to, subject, body text
message.setFrom(new InternetAddress("myemail#gmail.com"))
message.setRecipients(Message.RecipientType.TO, "myemail#gmail.com")
message.setSubject("First email")
message.setText(bodyText)
// And send it
Transport.send(message)
The error that I am getting is just
javax.mail.AuthenticationFailedException
I understand that I may need to provide a password somewhere but I am following the tutorial http://langref.org/scala/networking/smtp/send-an-email and they don't require password.
According to http://www.oracle.com/technetwork/java/faq-135477.html#smtpauth, you should use Transport.send(message, user, password)

Error empty content gmail using javamail api send email smtp

I'm working project : jsf, richfaces. I has just updated javamail api newest version 1.5.5 at https://java.net/projects/javamail/pages/Home
When i test send email from gmail to my gmail,
Subject : Subject test.
Content : Content test. And config : smtp.gmail.com, 465, SSL.
It has just subject and no content in my inbox receive gmail :
And log :
And my code :
try {
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
// Set the host smtp address
props.put("mail.smtp.host", SMTP_HOST_NAME);
props.put("mail.smtp.port", SMTP_PORT);
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.socketFactory.class", SSL_FACTORY);
props.put("mail.smtp.socketFactory.port", SMTP_PORT);
props.put("mail.smtp.ssl.trust", "*");
props.put("mail.smtp.ssl.socketFactory", sf);
} catch (GeneralSecurityException e) {
e.printStackTrace();
}
.......
.......
Authenticator auth = new SMTPAuthenticator();
Session session = Session.getInstance(props, auth);
session.setDebug(true);
// create a message
MimeMessage msg = new MimeMessage(session);
msg.setText("UTF8");
// set the from and to address
InternetAddress addressFrom = new InternetAddress(SMTP_AUTH_USER);
msg.setFrom(addressFrom);
System.out.println(addressFrom);
msg.setSubject(subject, "utf-8");
......
......
try {
String content = replaceCharacterInEmail(cus, null,null, message);
MimeBodyPart mbp1 = new MimeBodyPart();
mbp1.setContent(content, "text/html; charset=utf-8");
// attach the file to the message
Multipart mp = new MimeMultipart();
int count = 0;
if(files != null){
while (count < files.size()) {
MimeBodyPart mbdp = new MimeBodyPart();
mbdp.attachFile(files.get(count));
mp.addBodyPart(mbdp);
count++;
}
}
// create the Multipart and add its parts to it
mp.addBodyPart(mbp1);
// add the Multipart to the message
msg.setContent(mp);
Transport.send(msg);
} catch (Exception e) {
invalidAddress += (", " + address.trim());
e.printStackTrace();
}finally{
if (!"".equals(emailFails)) {
emailFails = emailFails.substring(1);
}
}
But, when i test above code at another project test (java application) with above lib javamail. It's ok :
.
I don't think problem at version of lib javamail. I don't know different between 2 project, because part send email is similar. How can i fix that error ?
Please observe this email structure:
-- multipart/mixed
-- mutlipart/alternative
-- text/plain
-- text/html
-- application/octet-stream (or any other mimetypes)
I found problem is conflict library at lib of jboss server and lib of app.ear (deploy).

Groovy MailService getting source code of sent email

I am using Groovy mailService for sending emails.
For logging purpose I want to get the plain text of the email sended (like you can see in an email programm).
Code:
mailService.sendMail {
async true
to mTo
subject mSubject
from mFrom
html outFile.getText()
}
Is it possible to get the generated mail?
Best regards,
Peter
Found a simple solution:
MimeMailMessage mailret = mailService.sendMail {
multipart true
async true
to mTo
subject mSubject
from mFrom
html mBody
attachBytes filename, filetype, outFile.getBytes()
}
mailret.mimeMessage.writeTo(System.out)
You can simulate what the service internally does by (do this in a service or somewhere available for Spring processing):
MailMessageBuilderFactory mailMessageBuilderFactory
GrailsApplication grailsApplication
...
def getMessage () {
Closure callable = {
async true
to mTo
subject mSubject
from mFrom
html outFile.getText()
}
MailMessageBuilder messageBuilder = mailMessageBuilderFactory.createBuilder(grailsApplication.config.grails.mail)
callable.delegate = messageBuilder
callable.resolveStrategy = Closure.DELEGATE_FIRST
callable.call(messageBuilder)
println messageBuilder.message // (your 'MailMessage' message printed out here)
}
For more see http://docs.spring.io/spring-framework/docs/2.0.x/api/org/springframework/mail/MailMessage.html

Writing an encrypted mail via Exchange Web Services

I would like to send an encrypted EMail Message with Exchange WEb Services using C#.
Is there any possibillity?
Thanks
Edit:
My Mail body encrypter:
public static byte[] encry(string body, ContentTyp typ, string to )
{
X509Certificate2 cert = GetMailCertificate(to);
StringBuilder msg = new StringBuilder();
msg.AppendLine(string.Format("Content-Type: text/{0}; charset=\"iso-8859-1\"", typ.ToString()));
msg.AppendLine("Content-Transfer-Encoding: 7bit");
msg.AppendLine();
msg.AppendLine(body);
EnvelopedCms envelope = new EnvelopedCms(new ContentInfo(Encoding.UTF8.GetBytes(msg.ToString())));
CmsRecipient recipient = new CmsRecipient(SubjectIdentifierType.IssuerAndSerialNumber, cert);
envelope.Encrypt(recipient);
//System.IO.MemoryStream ms = new System.IO.MemoryStream(envelope.Encode());
return envelope.Encode();
}
Main
byte [] con = encrypted.encry("test", encrypted.ContentTyp.plain, "test#server.com");
EmailMessage msg1 = new EmailMessage(_server);
msg1.MimeContent = new MimeContent("UTF-8", con);
msg1.ToRecipients.Add("user#server.com");
msg1.InternetMessageHeaders = ??
msg1.Send();
If you are referring to S/Mime encryption, then you'll have to create the encrypted message according to RFC 3852 and RFC 4134. After you've done that, you can send the message.
Using the EWS Managed API, this can be done as follows:
var item = new EmailMessage(service);
item.MimeContent = new MimeContent(Encoding.ASCII.HeaderName, content);
// Set recipient infos, etc.
item.Send();
EDIT:
You should add the standard headers like From, To, Date, Subject, etc. And the content-type.
Subject: Test
From: "sender" <sender#yourcompany.com>
To: "recipient" <recipient#othercompany.com>
Content-Type: application/pkcs7-mime; smime-type=signed-data; name=smime.p7m
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename=smime.p7m
Your encrypted body goes here
Just use a StringWriter put all that together. The result is your MIME body.