Unit Test for SendAsync Mail - c#

Today I am trying to create a unit test in visual studio for sending a email i am struggling with finding the best way to do it and using SendCompleted event as a validation for message been actually send.
Here i code i apply to send email but after using many different ways i just paste here clean code and maybe you can tell me what i am doing wrong or give me better way to solve it.
Here is my code what i have tried so far :
[TestClass]
public class sendEmailTest
{
[TestMethod]
public void sendAsyncEmailTest()
{
string from = "sender#test.com";
string to = "receiver#test.com";
MailMessage mail = new MailMessage(from, to);
mail.Subject = "Unit Test MVC";
mail.Body = "Unit Test for sending mail in MVC app";
mail.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.test.com";
smtp.EnableSsl = true;
NetworkCredential networkCredential = new NetworkCredential(from, "testpassword");
smtp.UseDefaultCredentials = true;
smtp.Credentials = networkCredential;
smtp.Port = 587;
smtp.SendAsync(mail, null);
smtp.SendCompleted += new SendCompletedEventHandler(smtp_SendCompleted);
}
static void smtp_SendCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
{
}
}

What you probably need is dummy dev SMTP server.
You can get it from here
Once it's running on your dev machine you can send emails setting smtp.Host to 'localhost' and using dummy email addresses.
However as mentioned in comments such unit test isn't useful at all as whether email is sent successful or not depends on many external factors like e.g network connection. If you past test on your local machine it does not mean sending email going to be successful every time on production server.

Related

SmtpClient Send(Mail) function timeout error

I am trying to send out an email to a mailing list that I have created, but when I run the function it just times out. I am not sure whether it is a host error or if I'm missing code or what. I am running an mvc format program on a local server.
I originally didn't have the credentials, but adding them changed nothing. Both before and after adding them all that happens is it loads for about a minute before reporting a timeout.
private void SendEmail(string sender, string[] attachments, List<string> recipients, ReleaseNotes notes, string username, string password)
{
SmtpClient client = new SmtpClient();
MailMessage mail = new MailMessage();
mail.Subject = "Software Release of VCM Version " + notes.ReleaseVersion;
mail.From = new MailAddress(sender);
mail.Body = GetEmailBody(notes);
mail.IsBodyHtml = true;
foreach (string r in recipients)
{
mail.To.Add(r);
}
foreach (string a in attachments)
{
mail.Attachments.Add(new Attachment(a));
}
client.Host = "pod51213.outlook.com";
client.Credentials = new NetworkCredential(username, password);
client.UseDefaultCredentials = false;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.Send(mail);
}
I am supposed to see the email appear in my inbox while the screen switches over to a screen saying email was sent. Its not giving me an actual error code. It just says operation timed out.
I was able to get the host I needed and get the function to run. The company I wrote the code for had their own host server. All I did to fix the code was delete the line that included client.Credentials, because I did not need that, and in the quotes for client.Host I replaced "pod51213.outlook.com" with "smtp.irco.com", which is the mail server for the company I built the program for.
I Think you should specify the port number
e.g.
SmtpClient("smtp.gmail.com", 587) // This for gmail

Failed to send an EMail with body contains ip address and port no

I have create function to send an email. This function was work successful on localhost but on server its failed without any exception. I know the problem comes from my Port on IP Address.
The sample body is string body = "<p>Please click here</p>Thank You."
The problem is : between IP Address and Port.
Successful send an email if i remove :.
Do you guys have any ideas?
public void Sent(string sender, string receiver, string subject, string body)
{
using (MailMessage mail = new MailMessage(sender, receiver))
{
using (SmtpClient client = new SmtpClient())
{
client.Port = 25;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Host = "mail.companyName.com.my";
mail.Subject = subject;
mail.IsBodyHtml = true;
mail.Body = body;
client.Send(mail);
}
}
}
You are doing it right, the code to send the mail is ok (you may want to revise the function name and make the smtp host name configurable, but that is not the point here).
The e-mail delivery fails on a relay, there is no immedieate feedback (no exception) to the client about this kind of failure.
The best bet is the IncreaseScoreWithRedirectToOtherPort property set in Set-HostedContentFilterPolicy in case your mail provider is Office365, or a similar spam filter mechanism in any other mail provider that is encountered down the mail delivery chain.
You can set a reply-to address and hope that the destination server will bounce a delivery failure that gives you more information. Or have the admin of the mail server look up the logs. More information here:
https://serverfault.com/questions/659861/office-365-exchange-online-any-way-to-block-false-url-spam
Try setting the 'mail.Body' to receive a Raw Html message instead of a encoded string, like:
mail.Body = new System.Web.Mvc.HtmlHelper(new System.Web.Mvc.ViewContext(), new System.Web.Mvc.ViewPage()).Raw(body).ToString();
Or put a using System.Web.Mvc at the beginning so it gets shorter and easier to understand:
using System.Web.Mvc
mail.Body = new HtmlHelper(new ViewContext(), new ViewPage()).Raw(body).ToString();

How can I change the "From" email address without a non-authenticated SMTP server?

All,
I'm writing an application that will allow customers to submit support tickets directly from their desktop. That being said, I'd like the "FROM" email address to be their email address.
I currently have the following code:
public void SendTicketEmail()
{
try
{
string tEmail = materialListView1.SelectedItems[0].SubItems[1].Text;
string tPhone = materialListView1.SelectedItems[0].SubItems[2].Text;
string tUser = materialListView1.SelectedItems[0].Text;
MailMessage mail = new MailMessage(tEmail, "my email");
SmtpClient client = new SmtpClient();
client.Port = 25;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Host = "smtp.simplifymsp.com";
mail.Subject = "this is a test email.";
mail.Body = "this is my test email body";
client.Send(mail);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
}
I'm assuming that my resolution at this point is to request that my hosting service enable an option where I can allow smtp outgoing emails without authentication on a specified port?
The alternative here is to have all of the support emails from each customer come from one of my preset email addresses and include a Customer ID in the subject, then create a workflow in my helpdesk ticketing system for each customer that assigns the customer's information to that ticket. That's more work than I care to do, especially when scaling.
Thank you in advance.
For what it's worth, I resolved this issue rather simply. FreshService (the website that I use for my ticketing system) reacts well with the following code:
mail.From = new MailAddress("me#me.com", "customer#customer.com");
Even though the email is coming from "me#me.com," FreshService still reads the ticket as if it came from the customer. Works beautifully.
Thank you all for your time.

send an email using SMTP without password in C#

I have a web application using ASP.net and C#,in one step it will need
from the user to
send an email to someone with an attachments.
my problem is when the user will send the email i don't want to put their
password every time the user send.
i want to send an email without the password of the sender.
any way to do that using SMTP ?
and this is a sample of my code "not all".
the code is worked correctly when i put my password , but without it ,it
is not work, i need a way to send emails without put the password but
in the same time using smtp protocol.
private void button1_Click(object sender, EventArgs e)
{
string smtpAddress = "smtp.office365.com";
int portNumber = 587;
bool enableSSL = true;
string emailFrom = "my email";
string password = "******";
string emailTo = "receiver mail";
string subject = "Hello";
string body = "Hello, I'm just writing this to say Hi!";
using (MailMessage mail = new MailMessage())
{
mail.From = new MailAddress(emailFrom);
mail.To.Add(emailTo);
mail.Subject = subject;
mail.Body = body;
mail.IsBodyHtml = true;
// Can set to false, if you are sending pure text.
// mail.Attachments.Add(new Attachment("C:\\SomeFile.txt"));
// mail.Attachments.Add(new Attachment("C:\\SomeZip.zip"));
using (SmtpClient smtp = new SmtpClient(smtpAddress,portNumber))
{
smtp.UseDefaultCredentials = true;
smtp.Credentials = new NetworkCredential(emailFrom, password);
smtp.EnableSsl = enableSSL;
smtp.Send(mail);
}
MessageBox.Show("message sent");
}
}
I believe this can be accomplished easily, but with some restrictions.
Have a look at the MSDN article on configuring SMTP in your config file.
If your SMTP server allows it, your email object's from address may not need to be the same as the credentials used to connect to the SMTP server.
So, set the from address of your email object as you already are:
mail.From = new MailAddress(emailFrom);
But, configure your smtp connection one of two ways:
Set your app to run under an account that has permission to access the SMTP server
Include credentials for the SMTP server in your config, like this.
Then, just do something like this:
using (SmtpClient smtp = new SmtpClient())
{
smtp.Send(mail);
}
Let the configuration file handle setting up SMTP for you. This is also great because you don't need to change any of your code if you switch servers.
Just remember to be careful with any sensitive settings in your config file! (AKA, don't check them into a public github repo)

Programmatic emails triggering "The server response was: 5.7.1 Unable to relay"

When I use outlook, I am able to send test email to my gmail address, however, when I do it from a console application it triggers : "The server response was: 5.7.1 Unable to relay"
using System.Net.Mail;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
MailMessage mail = new MailMessage("xxx#myCompany.com", "xxx#gmail.com");
SmtpClient client = new SmtpClient();
client.Port = 25;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Host = "xxx.xxx.com";
mail.Subject = "this is a test email.";
mail.Body = "this is my test email body";
client.Send(mail);
}
}
}
I verified that i have the correct client host through outlook. I also sent a test email to myself (from xx#mycompany to xx#mycompany) and that worked (although it sent it to the junk box). Why will it not let me send outgoing emails through this console app, but I can through the same address in outlook.
I'm pretty sure that if you have client.UseDefaultCredentials = false;, you need to set the credentials. At least that is what I do:
client.UseDefaultCredentials = false;
client.Credentials = new System.Net.NetworkCredential(someusername, somepassword);
edit: I should clarify, client.UseDefaultCredentials = false;, does not necessarily mean you need credentials listed, but if you are trying to send to an external domain (gmail.com), then your SMTP server will most likely require some type of SMTP Auth.

Categories

Resources