CSharp .Net Tutorial: Sending Email

James Cloud
Whether your are building your or personal email client, or even a commercial one, or if you simply want your application to send emails for any reason this tutorial will show you how. Using the new .Net Frameworks built in Internet and Mailing abilities you can easily send email using Visual CSharp .Net.

Following this simple tutorial will guide you through the steps of creating a basic emailing function that you can easily call and reuse at anytime during your applications runtime.

Sending Emails with CSharp .Net.

The first, and most vital, step to achieve the sending of emails through your CSharp .Net application is to code in a reference to System Net Mail. To do this just add this code right before your namespace:

using System.Net.Mail;

Now create a string void called WriteEmail using the source code given here:

public string WriteEmail(String Sender, String Recipient, String MessageBody, String MessageSubject, String SMTP)
{
try
{ //Attempt to create and send an email using the information supplied through the parameters
SmtpClient myClient = new SmtpClient(SMTP);
myClient.Send(Sender, Recipient, MessageSubject, MessageBody);
//If the message was sent successfully return the string "Sent"
return "Sent";
}
catch (SmtpException Err)
{
//There was an Error so Return the Error in String Format
return Err.Message;
}
}

Conclusion

To send an email with your newly created function simply call WriteEmail and supply the respective parameters. Here is an example:

if(WriteEmail(test@test.com, joe@test.com", "Test Message\r\nTest", "Test Message", "mail.mysmtp.com") == "Sent")
{
//If the Message was sent properly tell the user
MessageBox.Show("Sent");
}
else
{
//Show a Message if There was an Error
MessageBox.Show("Error Sending");
}

The above code will send a message to "test@test.com" from "joe@test.com" with the subject "test message" and the message "Test Message Test" using the smtp server "mail.mysmtp.com". It will also alert the user of the outcome of the operation.

Published by James Cloud

I like to program and do basically anything that has to do with technology and computers.  View profile

To comment, please sign in to your Yahoo! account, or sign up for a new account.