Send Mail Module

Download and share automation modules and examples.
User avatar
odklizec
Ranorex Guru
Ranorex Guru
Posts: 3922
Joined: Mon Aug 13, 2012 9:54 am
Location: Zilina, Slovakia

Re: Send Mail Module

Post by odklizec » Wed Aug 14, 2013 4:12 pm

Don't worry, I'm a C# noob too ;) Try this code, but you will have to adapt it according to your project setup and location of SendMail.cs:
test.CodeModules.SendMailModule SendM = new test.CodeModules.SendMailModule();
            SendM.SendMail();
where "test" is a name of my project (namespace) and "CodeModules" is the name of custom folder, where I usually add code modules. As for "SendM", you can change this string to whatever you want.

This is how it looks in my test project...
SendMail.png
SendMail.png (26.57 KiB) Viewed 3792 times
Hope this helps a bit?
Pavel Kudrys
Ranorex explorer at Descartes Systems

Please add these details to your questions:
  • Ranorex Snapshot. Learn how to create one >here<
  • Ranorex xPath of problematic element(s)
  • Ranorex version
  • OS version
  • HW configuration

leonou1987
Posts: 1
Joined: Mon Nov 04, 2013 3:48 pm

Re: Send Mail Module

Post by leonou1987 » Mon Nov 04, 2013 4:03 pm

Hi,there

I've convert your SendMail.cs to .vb version, cause I'm using VB.net for our testing project, I placed my module in our test suite project, and modified all the variables you've mentioned before, after that I don't konw how to continue :shock: :?: , should I directly run the project ?... so...could anyone tell me exactly the working steps of using this module ?

Thanks a lot :D

User avatar
Support Team
Site Admin
Site Admin
Posts: 11709
Joined: Fri Jul 07, 2006 4:30 pm
Location: Graz, Austria

Re: Send Mail Module

Post by Support Team » Fri Nov 08, 2013 4:11 pm

Hello leonou,

It could be that it is not working in your case since SendMail.cs file was uploaded a long time ago.
You should find anything you need in this post (see page 1).
Simply call your method at the end of your test after your report is stored.

Please note that we don't have a step-by-step guide but it should be easy to implement it.

Regards,
Markus (T)
.
Image

Swisside
Posts: 92
Joined: Thu Oct 10, 2013 10:40 am

Re: Send Mail Module

Post by Swisside » Fri Nov 08, 2013 4:17 pm

Hey.

Just spend couple minutes setting up this cool functionality. It works quite nicely !

@leonou1987

I'm using Gmail SMTP server to send the mail with the report attached.

Howto (in c# but I'm pretty sure you can convert in VB.NET once the C# version works for you :) )

1) Add a new code module (Mine is called SendMailGmail.cs)

2) Add the following method to it
public void SendMail()
		{
			var fromAddress = new MailAddress("[email protected]", "From Name");
			var toAddress = new MailAddress("[email protected]", "To Name");
			const string fromPassword = "mygmailpassword";
			const string subject = "test";
			const string body = "test";
			string zipFileName = Ranorex.Core.Reporting.TestReport.ReportEnvironment.ReportZipFilePath;
			var smtp = new SmtpClient
			{
				Host = "smtp.gmail.com",
				Port = 587,
				EnableSsl = true,
				DeliveryMethod = SmtpDeliveryMethod.Network,
				UseDefaultCredentials = false,
				Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
			};
			
			using (var message = new MailMessage(fromAddress, toAddress)
			       {
			       	Subject = subject,
			       	Body = body
			       })
			
			
			// adds the zipped report to the mail
			if (System.IO.File.Exists(zipFileName))
			{
				System.Net.Mail.Attachment MyReport = new System.Net.Mail.Attachment(zipFileName);
				message.Attachments.Add (MyReport);
				smtp.Send(message);
			}
						
		}
3) As suggested by odklizec edit Program.cs with the following information
(...)
catch (Exception e)
            {
                Report.Error("Unexpected exception occurred: " + e.ToString());
                error = -1;
            }
            YourNameSpace.CodeModules.SendMailGmail sendMail = new CodeModules.SendMailGmail();
            sendMail.SendMail();
            return error;

Hope it will help you :)

Swiss'
A simple thank you always does wonders !

cdwillis911
Posts: 5
Joined: Fri Oct 18, 2013 9:24 pm

Send mail module issues

Post by cdwillis911 » Fri Nov 15, 2013 4:29 pm

Hi all,

I'm fairly new to Ranorex and C# in general, so please bare with me on this. I'm attempting to set up functionality that will email out the compressed report file once the script completes. I have imported the SendMail.cs module into my program, and it works fine as long as I set it up as a test case; however, it obviously is unable to send the report due to the script not being completed and thus the full report not generated.

I am following the directions given in this thread (send-mail-module-t2356-15.html) in terms of attaching the report file to the email and then calling the module at the end of Program.cs in the location specified.

Where I am getting stuck is the call in Program.cs which is explained in the first post on the 2nd page of that thread (by author "odklizec"). I attempted to add that piece of code to my script, which I changed to fit the structure of my test suite, and I am getting the following error message upon compile:

"The type or namespace name 'SendMailModule' does not exist in the namespace 'ServiceXG_smoke' (are you missing an assembly reference?) (CS0234)"

One thing I notice is that when I type "ServiceXG_smoke" and then a "." in the code editor for Program.cs, I can see all of my other recording modules show up in the window except for "SendMailModule". Is there an additional step I have to take somewhere for Program.cs to be able to read this correctly?

Thanks,

Chris

Swisside
Posts: 92
Joined: Thu Oct 10, 2013 10:40 am

Re: Send Mail Module

Post by Swisside » Mon Nov 18, 2013 3:43 pm

Hello Chris

Did you read my previous post ?

The only thing you need to do for it to work is replace "YourNameSpace" (in Program.cs) with the name of your own namespace. (You can see it at the beginning of any module/code module)

Regards


Boris
A simple thank you always does wonders !

cdwillis911
Posts: 5
Joined: Fri Oct 18, 2013 9:24 pm

Re: Send Mail Module

Post by cdwillis911 » Fri Nov 22, 2013 7:03 pm

Swisside wrote:Hello Chris

Did you read my previous post ?

The only thing you need to do for it to work is replace "YourNameSpace" (in Program.cs) with the name of your own namespace. (You can see it at the beginning of any module/code module)

Regards


Boris
Boris,

Thanks for the reply. The issue I was having was that I could not get "SendMailModule" to appear in the box that appears after I enter my namespace (ServiceXG_smoke) followed by a "." in Program.cs. To correct this, I went into SendMail.cs and changed the namespace and I am now able to access this module in Program.cs.
Capture.JPG
Capture.JPG (25.72 KiB) Viewed 3535 times
I then added the code based on the examples given in this thread to Program.cs and it is working perfectly!

I do have one other issue though - I have a data source that I'd like to incorporate into this code module in order to pull the variables from a spreadsheet instead of hard coding them in SendMail.cs. If I run the code module from a test case with a defined data source and data bindings, it works fine, but since I need to attach a report to it, I have to run it in Program.cs. When I run it from Program.cs, I receive an error message in the command prompt window related to a null value for "To", "From", etc, so obviously it is not reading the data binding from my test case.

Is there a way I can somehow use my spreadsheet data in this code module once it is integrated into Program.cs?

Thanks,

Chris

cdwillis911
Posts: 5
Joined: Fri Oct 18, 2013 9:24 pm

Re: Send Mail Module

Post by cdwillis911 » Fri Nov 22, 2013 9:43 pm

Scratch that last post. I figured out what I needed to do to assign variables.

If anyone is interested, I created a csv file called "test.csv" and added the following code to read values from the file:

var reader = new StreamReader(File.OpenRead("test.csv"));
var line = reader.ReadLine();
var values = line.Split(',');

string fromEmail = values[0];
string toEmail = values[1];
string smtpServer = values[2];
string smtpPort = values[3];

I then replaced the existing variables in the code module with the ones above.

Thanks everyone for pointing me in the right direction on this.

amit_kumar01
Posts: 11
Joined: Tue Dec 23, 2014 1:15 pm

Re: Send Mail Module

Post by amit_kumar01 » Tue Dec 23, 2014 1:21 pm

Hi Support,

I am trying to send mail after each execution but i am getting this as a error message.

The code which i am using is same as you have mentioned i.e.

"/*
* Created by Ranorex
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.Drawing;
using System.Threading;
using System.Windows.Forms;
using System.Net.Mail;

using Ranorex;
using Ranorex.Core;
using Ranorex.Core.Testing;

namespace Ranorex.Modules
{
/// <summary>
/// Use this module at any position of your test suite to get informed about test runs by email.
/// This is especially useful for overnight test executions on runtime machines.
/// </summary>
[TestModule("EEE7C8D8-D950-40EF-B24A-1A9A87C0DA21", ModuleType.UserCode, 1)]
public class SendMailModule : ITestModule
{
/// <summary>
/// Constructs a new instance.
/// </summary>
public SendMailModule()
{
// Do not delete - a parameterless constructor is required!
}

#region Variables

string _to = "";

[TestVariable("D089186D-7919-4023-8165-B68F9151C6A7")]
public string To
{
get { return _to; }
set { _to = value; }
}

string _from = "";

[TestVariable("BDB3FC8C-1E51-448F-9049-AEF0B247DBDB")]
public string From
{
get { return _from; }
set { _from = value; }
}

string _subject = "Ranorex Module Report";

[TestVariable("398FF772-C15C-4b91-954B-34CC636DEDC9")]
public string Subject
{
get { return _subject; }
set { _subject = value; }
}

string _serverHostName = "smtp.gmail.com";

[TestVariable("0EE4CB1E-D738-4DE8-B122-92B3CCE6F70C")]
public string ServerHostname
{
get { return _serverHostName; }
set { _serverHostName = value; }
}

string _serverPort = "25";

[TestVariable("4C6A889D-BACE-4AE1-9EEF-40EA26775574")]
public string ServerPort
{
get { return _serverPort; }
set { _serverPort = value; }
}

string _message = "Test Report";

[TestVariable("D49672F4-3021-4460-96DA-2EC11AE318A8")]
public string Message
{
get { return _message; }
set { _message = value; }
}

#endregion

void ITestModule.Run()
{
SendMail();
}

void SendMail()
{
try
{
MailMessage mail = new MailMessage("[email protected]", "[email protected]", Subject, Message);
SmtpClient smtp = new SmtpClient(ServerHostname, int.Parse(ServerPort));
smtp.Credentials = new System.Net.NetworkCredential("sample username", "sample password");
smtp.Send(mail);

Report.Success("Email has been sent to '" + To + "'.");
}
catch(Exception ex)
{
Report.Failure("Mail Error: " + ex.ToString());
}
}
}
}
"

"Mail Error: System.Net.Mail.SmtpException: The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.0 Must issue a STARTTLS command first. o10sm19811782pdr.96 - gsmtp
at System.Net.Mail.MailCommand.CheckResponse(SmtpStatusCode statusCode, String response)
at System.Net.Mail.MailCommand.Send(SmtpConnection conn, Byte[] command, MailAddress from, Boolean allowUnicode)
at System.Net.Mail.SmtpTransport.SendMail(MailAddress sender, MailAddressCollection recipients, String deliveryNotify, Boolean allowUnicode, SmtpFailedRecipientException& exception)
at System.Net.Mail.SmtpClient.Send(MailMessage message)".

krstcs
Ranorex Guru
Posts: 2683
Joined: Tue Feb 07, 2012 4:14 pm
Location: Austin, Texas, USA

Re: Send Mail Module

Post by krstcs » Tue Dec 23, 2014 4:59 pm

The error message says that your server requires TLS, but you haven't turned it on in your code.

You can try using the following to start SSL/TLS connection:

Code: Select all

SmtpClient smtp = new SmtpClient(ServerHostname, int.Parse(ServerPort));
smtp.Credentials = new System.Net.NetworkCredential("sample username", "sample password");

//add the following line before Send()
smtp.EnableSsl = true;

smtp.Send(mail);
Shortcuts usually aren't...

amit_kumar01
Posts: 11
Joined: Tue Dec 23, 2014 1:15 pm

Re: Send Mail Module

Post by amit_kumar01 » Wed Dec 24, 2014 5:06 am

Hi krstcs,

After adding, the result is same. Again i am getting the same error i.e.

"Mail Error: System.Net.Mail.SmtpException: The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required."

SmtpClient smtp = new SmtpClient(ServerHostname, int.Parse(ServerPort));
smtp.Credentials = new System.Net.NetworkCredential("sample username", "sample password");
smtp.EnableSsl = true;
smtp.Send(mail);

krstcs
Ranorex Guru
Posts: 2683
Joined: Tue Feb 07, 2012 4:14 pm
Location: Austin, Texas, USA

Re: Send Mail Module

Post by krstcs » Wed Dec 24, 2014 3:34 pm

My guess would be that your server requires a secure connection from the start, while SmtpClient can't start off with a secure connection. It must start with an unsecure connection and then "upgrade" after the connection starts. This would mean that SmtpClient can't be used with your server without the server administrator changing the server's smtp connection settings, which I highly doubt they will do.
Shortcuts usually aren't...

amit_kumar01
Posts: 11
Joined: Tue Dec 23, 2014 1:15 pm

Re: Send Mail Module

Post by amit_kumar01 » Tue Jan 06, 2015 1:25 pm

Hi krstcs,

Thanks now i am able to send mail. How can i send report within that mail(as an attachment).
I am using this code.

"MailMessage mail = new MailMessage("sample_from", "sample_to", Subject, Message);

SmtpClient smtp = new SmtpClient(ServerHostname, int.Parse(ServerPort));

// to send attachment.
mail.Body = "mail with attachment";

System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment("WithAttachment_20150106.rxlog");

//We also have to send these below files with rxlog but how?

//attachment = new System.Net.Mail.Attachment("RanorexReport4.css");
//attachment = new System.Net.Mail.Attachment("RanorexReport4.png");
//attachment = new System.Net.Mail.Attachment("RanorexReport4.xsl");
//attachment = new System.Net.Mail.Attachment("WithAttachment_20150106.rxlog.data");
mail.Attachments.Add(attachment);



//smtp.Credentials = new System.Net.NetworkCredential("username", "pwd");
smtp.EnableSsl = false;
smtp.Send(mail);

Report.Success("Email has been sent to '" + To + "'.");
}
catch(Exception ex)
{
Report.Failure("Mail Error: " + ex.ToString());
}
}

krstcs
Ranorex Guru
Posts: 2683
Joined: Tue Feb 07, 2012 4:14 pm
Location: Austin, Texas, USA

Re: Send Mail Module

Post by krstcs » Tue Jan 06, 2015 2:25 pm

You can't attach the report while it is still open. You will need to close the report and then send it.

I would recommend that you use a continuous integration solution such as Jenkins instead of trying to do this in Ranorex. Jenkins has plugins that allow you to send email and publish reports to Jenkins' web server so anyone can view them.
Shortcuts usually aren't...

amit_kumar01
Posts: 11
Joined: Tue Dec 23, 2014 1:15 pm

Re: Send Mail Module

Post by amit_kumar01 » Wed Jan 07, 2015 8:19 am

Hi Support,

Is this possible to attach all file at a time? Because we need 4 more files to view the rxlog file i.e. .css, .xsl, .png and .data file without these files we can't view test execution report.

Or is there any alternate method to send all test report files at a time to the mentioned email id after test suit execution itself? Because we are running overnight and we want that test report to our mail to check which test case fail or pass.

With Regards,
Amit kumar
CAMO Software