Mr Cricket
Mr Cricket

Reputation: 483

How to test asp.net email is being sent

I have some code in my asp.net which sends an email:

public void SendEmail(string message)
{
    var body = message;

    var email = new MailMessage(ConfigurationManager.AppSettings["SenderEmail"],
                            ConfigurationManager.AppSettings["RecipientEmail"],
                            "Email Test", body);

    var client = new SmtpClient();
    client.Host = Properties.Settings.Default.smtp;
    client.DeliveryMethod = SmtpDeliveryMethod.Network;
    client.Credentials = CredentialCache.DefaultNetworkCredentials;

    client.Send(email);
}

I'm wanting to know how to test this. Whether it is a unit test or integration test I really just don't care. I'm NOT wanting to mock this out. I'm actually wanting to write a test that an email is sent with the correct message.

Can anyone help me with this?

Upvotes: 6

Views: 8585

Answers (5)

llewellyn falco
llewellyn falco

Reputation: 2351

There is a very simple way to test the resulting email in approvaltests. You need to separate the method into 2 methods, one that creates the email, one that sends the email. Then you can call.

EmailApprovals.Verify(mail)

There's a video showing the process here: http://www.youtube.com/watch?v=Sf16dPq2n3w

Upvotes: 0

IrishChieftain
IrishChieftain

Reputation: 15253

Just create a folder called "maildrop" on your c:/ drive and use the following in your Web.config file:

<mailSettings>
    <smtp deliveryMethod='SpecifiedPickupDirectory'>
        <specifiedPickupDirectory pickupDirectoryLocation="c:\maildrop" />
    </smtp>
</mailSettings>

More information:

http://weblogs.asp.net/gunnarpeipman/archive/2010/05/27/asp-net-using-pickup-directory-for-outgoing-e-mails.aspx

Upvotes: 13

antoniuslin
antoniuslin

Reputation: 249

to setup an automated test you'll want to have a test email address on a server you can query (since topic is asp.net, we'll assume exchange server), then query the mailbox for the email you're looking for using:

opt 1: exchange sdk

opt 2: through web requests (if the exchange server's http connector is enabled

opt 3: write your own simple pop3 client/cli/api

ref for opt 3: http://www.codeproject.com/KB/IP/popapp.aspx

Upvotes: 0

Bimmy
Bimmy

Reputation: 718

Send an email to yourself and see if you received it?

If you don't know how to do that you probably want to go back to basics.

Upvotes: 1

griegs
griegs

Reputation: 22760

Can't you place this within a module and call it from a test and set the recipient to say you're email address. if you get the email then i'd say it's working.

Upvotes: -1

Related Questions