Thursday, July 16, 2009

Sending email through System.Net.Mail.Smtpmail in asp.net 3.5/2.0


For any web application or website the sending email is a necessity for newsletter, invitation or reset password for everything we have to sent a mail to the people. So we need to see how we can send mail. In 1.1 we are sending emails with System.Web.Mail.SmtpMail which is now obsolete. Now in asp.net 2.0 or higher version there is a namespace called System.Net.Mail.Smtpmail in asp.net 3.5. With this namespace we can easily write a code to send mail within couple of minutes.

If you want to sent a mail first thing you need is smtpserver. Smtpserver is a server which will route and send mail to particular system. To use smtpserver we need to configure some settings in web.config following is the setting for the web.config.

<system.net>

    <mailsettings>

       <smtp deliveryMethod="Network">

         <network host="stmp server address or ip"

           port="Smtp port" defaultCredentials="true"/>

        </smtp>     

    </mailsettings>

</system.net>


Here you need to set the all the smtp configuration. This will be used by the smptclient by default. Here is the code for sending email in asp.net 3.5

SmtpClient smtpClient = new SmtpClient();

MailMessage message = new MailMessage();

try

{

   MailAddress fromAddress = new MailAddress("from@site.com","Nameofsendingperson");

   message.From = fromAddress;//here you can set address

   message.To.Add("to@site.com");//here you can add multiple to

   message.Subject = "Feedback";//subject of email

   message.CC.Add("cc@site.com");//ccing the same email to other email address

   message.Bcc.Add(new MailAddress("bcc@site.com"));//here you can add bcc address

   message.IsBodyHtml = false;//To determine email body is html or not

   message.Body =@"Plain or HTML Text";

   smtpClient.Send(message);

}

catch (Exception ex)

{

   //throw exception here you can write code to handle exception here

}


So from above simple code you can add send email to anybody
Adding Attachment to the email:If you want to attach some thing in the code then you need to write following code.

message.Attachments.Add(New System.Net.Mail.Attachment(Filename));


Here file name will the physical path along with the file name. You can attach multiple files with the mail.

Sending email with Authentication: If you want to sent a email with authentication then you have to write following code.

System.Net.Mail.SmtpClient mailClient = new System.Net.Mail.SmtpClient();

     //This object stores the authentication values

     System.Net.NetworkCredential basicCrenntial = 
          new System.Net.NetworkCredential("username", "password");

     mailClient.Host = "Host";

     mailClient.UseDefaultCredentials = false;

     mailClient.Credentials = basicCrenntial;

     mailClient.Send(message);



Happy Coding…
Share:

19 comments:

  1. What is the namespace for SmtpClient()

    ReplyDelete
  2. This comment has been removed by a blog administrator.

    ReplyDelete
  3. Does anyone have a solution for this issue? It is driving me crazy! I open the script editor, close, build, reopen, close, build, save and still the same result every time!!

    Date 7/15/2010 2:43:38 PM
    Log Job History (SSIS_EMAIL_QUEUE_SendEmail)

    Step ID 1
    Server KING\SQL2008
    Job Name SSIS_EMAIL_QUEUE_SendEmail
    Step Name SendMail dev
    Duration 00:00:07
    Sql Severity 0
    Sql Message ID 0
    Operator Emailed
    Operator Net sent
    Operator Paged
    Retries Attempted 0

    Message
    Executed as user: KING\SYSTEM. Microsoft (R) SQL Server Execute Package Utility Version 10.0.2531.0 for 32-bit Copyright (C) Microsoft Corp 1984-2005. All rights reserved. Started: 2:43:38 PM Error: 2010-07-15 14:43:45.33 Code: 0x00000004 Source: Send HTML Email Description: The binary code for the script is not found. Please open the script in the designer by clicking Edit Script button and make sure it builds successfully. End Error Error: 2010-07-15 14:43:45.33 Code: 0xC0024107 Source: Send HTML Email Description: There were errors during task validation. End Error DTExec: The package execution returned DTSER_FAILURE (1). Started: 2:43:38 PM Finished: 2:43:45 PM Elapsed: 6.75 seconds. The package execution failed. The step failed.

    ReplyDelete
  4. This comment has been removed by a blog administrator.

    ReplyDelete
  5. Hi,
    I tried sending an email from my web application using the above code but I am getting this error message.
    No connection could be made because the target machine actively refused it 127.0.0.1:25
    Unable to connect to remote server.
    failure sending mail.

    I have set the host as localhost and port 25. authentication is checked as not required.
    Please help.

    ReplyDelete
  6. Hi. I have used the code above to send an authenticated email for a contact form on my web site.

    I get Mailbox unavailable. The server response was: bosauthsmtp08: Host IP Address Here: No unauthenticated relaying permitted.

    My code is as follows:

    SmtpClient client = new SmtpClient();
    MailMessage mail_msg = new MailMessage();

    MailAddress fromAdd = new MailAddress(txtEmail.Text.Trim(), txtName.Text.Trim());
    mail_msg.From = fromAdd;
    mail_msg.To.Add("contact@mydomain.com");
    mail_msg.Subject = "Contact Me";
    mail_msg.IsBodyHtml = true;
    mail_msg.Body = "Message From: " + txtName.Text.Trim() + "
    Subject:" + lstSubjects.SelectedValue.ToString() + "
    Email: " + txtEmail.Text.Trim() + "
    Comment: " + txtQuestion.Text.Trim();

    System.Net.NetworkCredential basicCredential = new System.Net.NetworkCredential("contact@mydomain.com", "******");

    client.Host = "smtp.mydomain.com";
    client.UseDefaultCredentials = false;
    client.Credentials = basicCredential;

    client.Send(mail_msg);

    I do have the Smtp code in the webconfig file incase that matters.

    Any help would be greatly appreciated.

    Dennis

    ReplyDelete
  7. Hi Hima,

    I think there is some thing wrong with the SMTP Server configuration. Please try google smtp as its provided as free and then try it.

    Best Regards,
    Jalpesh

    ReplyDelete
  8. Hello Dennis,

    I think your password is wrong that why realy is not authenticated.

    Best Reagrds,
    Jalpesh

    ReplyDelete
  9. I use given below code to sending the mail but it not work please correct it o that it can send mail properly after deployeing web application on server.


    try
    {

    string newlinw = "";
    string mbody = txtName.Text + newlinw + "Mobile No:- " + txtMobileNumber.Text + newlinw + "Email:- " + txtEmailId.Text + newlinw + "Adress:-" + txtAddress.Text + newlinw + "Comment:- " + txtComment.Text;
    string sub = "Enquiry For " + lblName.Text + "";
    System.Net.Mail.MailMessage mymail = new System.Net.Mail.MailMessage();
    System.Net.Mail.SmtpClient myclient = new System.Net.Mail.SmtpClient();
    System.Net.Mail.MailAddress from = new System.Net.Mail.MailAddress("info@rudravaastu.com");

    myclient.Host = "mail.rudravasstu.com";
    mymail.IsBodyHtml = true;
    myclient.Port = 25;
    mymail.From = from;
    mymail.To.Add(from);
    mymail.Subject = sub;
    mymail.Body = mbody;
    myclient.Send(mymail);


    }
    catch (Exception)
    {
    Response.Write("Exception Ocure Try Again Later");

    }

    ReplyDelete
  10. One way of preventing System.Net.Mail in sending mail is antivirus software specifically McAfee.

    http://jewernest.clanteam.com/?p=20

    ReplyDelete
  11. i m using same code but still under given error occure...

    [The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.0 Must issue a STARTTLS command first. x1sm667554pbb.2]

    what it means????

    ReplyDelete
  12. @Anonymous

    I think this is because you are not providing SSL enable=true while you are doing coding.

    Get correct requirement for you hosting provider and then it will be working.

    ReplyDelete
  13. This comment has been removed by a blog administrator.

    ReplyDelete
  14. Hi,I have used the above code in web.config file but getting error
    for mailsetting
    Error 3 Unrecognized configuration section system.net/mailsettings.

    ReplyDelete
  15. @f2f9583da96207635a2f30c9114ee4e6 Which .net framework version you are using there?. Please provide me whole web.config code

    ReplyDelete
  16. This comment has been removed by a blog administrator.

    ReplyDelete
  17. very good coding for mailing

    ReplyDelete
  18. @Vikash kumar - Thanks for compliments!!

    ReplyDelete

Your feedback is very important to me. Please provide your feedback via putting comments.

Support this blog-Buy me a coffee

Buy me a coffeeBuy me a coffee
Search This Blog
Subscribe to my blog

  

My Mvp Profile
Follow us on facebook
Blog Archive
Total Pageviews