OdeToCode IC Logo

Sending email from an ASP.Net web form using SmtpMail

Thursday, January 1, 2004

Sending an email from a web page is something which is required in just about every application. This is a generic email class part of a class library we use.
We are going to use the SmtpMail class, which is a part of the System.Web.Mail  namespace. It has just one method – ‘send’ and this is what we use by passing an instance of the mail MailMessage class.
The MailMessage class has a number of members, most of them are self-explanatory, but if you want any more information http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemwebmailmailmessagememberstopic.asp. We are just going to use a few of them for this example.

using System.Web.Mail;

namespace Utility
public class EmailClass
    {   protected string Sender;
        protected string Recipient;
        protected string Subject;
        protected string Attachment;
        protected string Message;
        public EmailClass(string Sender,
                  string Recipient, 
                  string Subject,
                  string Message,
                  string Attachment) {
            this.Sender    = Sender;
            this.Recipient = Recipient;
            this.Subject   = Subject;
            this.Message   = Message;
            this.Attachment= Attachment;       
        public void SendEmail() {
             MailMessage mail = new MailMessage();
             mail.From = Sender;
             mail.To = Recipient;
             mail.Subject = Subject;
// I chose the mail format as to be plain text but you can choose
// to have the message sent in HTML format by using
             mail.BodyFormat = MailFormat.Text;
             if (Attachment != "") {
// MailAttachment constructor
               MailAttachment mailAttachment = new mailAttachment(Attachment);
   SmtpMail.SmtpServer = “smptServerName”;

You might see this error message
System.Runtime.InteropServices.COMException (0x8004020E): The server rejected the sender address. The server response was: 454 5.7.3 Client does not have permission to submit mail to this server.
Exchange doesn't allow unauthenticated users to send mail via SMTP to prevent against spammers, etc.  
It seems that Everett the next version of the .NET framework will take care of this problem – there is a Fields property for the mailMessage class which let you get an authentication code from CDOSYS