Furkan Gözükara
Furkan Gözükara

Reputation: 23800

Proper email sending class asp.net 4.0 IIS 7.5 SMTP

Does anybody have proper email sending class for asp.net 4.0 c# ?

Currently i have something like below

What suggestions would you make this below class ?

public static string sendEmail(string srEmailAddress, string srFrom, string srSubject, string srBodyHTML, string srBodyText)
{
    using (MailMessage Email = new MailMessage(new MailAddress("[email protected]", srFrom), new MailAddress(srEmailAddress)))
    {
        Email.IsBodyHtml = true;
        Email.SubjectEncoding = Encoding.UTF8;
        Email.BodyEncoding = Encoding.UTF8;
        Email.Subject = srSubject;

        using (AlternateView textPart = AlternateView.CreateAlternateViewFromString(srBodyText, Encoding.UTF8, "text/plain"))
        {
            textPart.TransferEncoding = System.Net.Mime.TransferEncoding.QuotedPrintable;
            Email.AlternateViews.Add(textPart);
        }

        using (AlternateView htmlPart = AlternateView.CreateAlternateViewFromString(srBodyHTML, Encoding.UTF8, "text/html"))
        {
            htmlPart.TransferEncoding = System.Net.Mime.TransferEncoding.QuotedPrintable;
            Email.AlternateViews.Add(htmlPart);
        }

        try
        {
            using (SmtpClient smtpClient = new SmtpClient())
            {
                smtpClient.Host = "127.0.0.1";
                smtpClient.Port = 25;
                smtpClient.Send(Email);
                return "True";
            }
        }
        catch (Exception E)
        {
            return E.Message.ToString();
        }
    }
}

c# 4.0 asp.net 4.0 IIS 7.5

Upvotes: 1

Views: 1565

Answers (1)

Dave Zych
Dave Zych

Reputation: 21887

SmtpClient is correct. FYI, you can specify the Host and Port in the constructor, but other than that it's fine.

using (SmtpClient smtpClient = new SmtpClient("127.0.0.1", 25))
{
    smtpClient.Send(Email);
    return true;
}

I would change the return type though... either return a bool of true or false, or make the return type void and catch the exception in the calling code.

EDIT: To answer your question about catching the exception... Instead of catching an Exception inside of your sendEmail method (which should be SendEmail to follow the C# naming standards, by the way), you should catch the exception from where you call sendEmail.

try
{
    sendEmail(/*whatever parameters you need */);
}
catch(Exception e)
{
    //Do whatever you need to do with the exception... Display a notification
    // to the user, etc
}

Also, you should try not to catch all exceptions - only the ones you are expecting - which in this case is most likely an SmtpException.

Upvotes: 3

Related Questions