Click here to Skip to main content
15,889,838 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
Hi I am new in learning C #, I want to ask how to send email through C #, Please Help Me :( , I need to quickly.
Thanks.
Posted

use this method


C#
using System.Net.Mail;
namespace Common
{
    public class SendEmail
    {
    public static void SendMessage(string subject, string messageBody, string toAddress, string ccAddress)
        {
            MailMessage message = new MailMessage();
            SmtpClient client = new SmtpClient();

            // Set the sender's address
            message.From = new MailAddress("fromAddress");

         // Allow multiple "To" addresses to be separated by a semi-colon
            if (toAddress.Trim().Length > 0)
            {
                foreach (string addr in toAddress.Split(';'))
                {
                    message.To.Add(new MailAddress(addr));
                }
            }
          // Allow multiple "Cc" addresses to be separated by a semi-colon
            if (ccAddress.Trim().Length > 0)
            {
                foreach (string addr in ccAddress.Split(';'))
                {
                    message.CC.Add(new MailAddress(addr));
                }
            }
            // Set the subject and message body text
            message.Subject = subject;
            message.Body = messageBody;

            // Set the SMTP server to be used to send the message
            client.Host = "YourMailServer";

            // Send the e-mail message
            client.Send(message);
        }
    }
}
 
Share this answer
 
v3
 
Share this answer
 
Comments
[no name] 1-Nov-12 3:40am    
Nice Collection:)
Sushil Mate 1-Nov-12 3:44am    
thanks onurag.
Sachin MCA2012 18-Dec-12 12:24pm    
sir how cant i find the port number on my system ..can i send mail on gmail account
free of cost from my asp.net application please provide me the code the above code doesnt work on my system
Sushil Mate 18-Dec-12 23:42pm    
whats the error? you can send mail to your gmail account. please elaborate your problem?
Please use the code below which is a MailClass.cs and try using the functions in the same within your code behind:(where you want to SendMail())
using System;
using System.Net.Mail;
//using System.Web.Mail;

/// <summary>
/// Summary description for commonClass
/// </summary>
public class mailClass
{
    #region Declaration
    string retMsg = "";
    private string m_toEmail;
    private string m_fromEmail;
    private string m_displayName;
    private string m_subject;
    private string m_body;
    private string m_bcc;
    private Attachment m_attachment;
    const string c_success = "success";
    const string c_error = "error";
    #endregion 

    public mailClass()
    {
        //
        // TODO: Add constructor logic here
        //
    }

    #region Properties
    public string vToEmail
    {
        get
        {
            return m_toEmail;
        }
        set
        {
            if (value != m_toEmail)
            {
                m_toEmail = value;
            }
        }
    }

    public string vFromEmail
    {
        get
        {
            return m_fromEmail;
        }
        set
        {
            if (value != m_fromEmail)
            {
                m_fromEmail = value;
            }
        }
    }
    public string vDisplayName
    {
        get
        {
            return m_displayName;
        }
        set
        {
            if (value != m_displayName)
            {
                m_displayName = value;
            }
        }
    }
    public string vSubject
    {
        get
        {
            return m_subject;
        }
        set
        {
            if (value != m_subject)
            {
                m_subject = value;
            }
        }
    }
    public string vBody
    {
        get
        {
            return m_body;
        }
        set
        {
            if (value != m_body)
            {
                m_body = value;
            }
        }
    }
    public Attachment vAttachment
    {
        get
        {
            return m_attachment;
        }
        set
        {
            if (value != m_attachment)
            {
                m_attachment = value;
            }
        }
    }



    public string vBcc
    {
        get
        {
            return m_bcc;
        }
        set
        {
            if (value != m_bcc)
            {
                m_bcc = value;
            }
        }
    }
    #endregion

    #region Function
    public string SendMail()
    {
        try
        {
            MailAddress from = new MailAddress(m_fromEmail, "World Class Medals");
            MailMessage message = new MailMessage();
            SmtpClient emailClient = new SmtpClient("smtp.appliedi.net");
            System.Net.NetworkCredential SMTPUserInfo = new System.Net.NetworkCredential("", "");
            emailClient.UseDefaultCredentials = false;
            emailClient.Credentials = SMTPUserInfo;
            if (m_toEmail.Contains(";"))
            {
                message = new MailMessage();
                string[] addrCollection = m_toEmail.Split(";".ToCharArray());
                string mailList = "";
                foreach (string addr in addrCollection)
                    mailList = mailList + "<" + addr + "> ,";
                mailList = mailList.TrimEnd(",".ToCharArray());
                MailAddress to = new MailAddress(mailList);
                message = new MailMessage(from, to);
            }
            else
            {
                MailAddress to = new MailAddress(m_toEmail);
                message = new MailMessage(from, to);
            }
            if (m_bcc != null)
            {
                MailAddress bcc = new MailAddress(m_bcc);
                message.Bcc.Add(bcc);
            }
            message.IsBodyHtml = true;
            message.Subject = m_subject;
            message.Body = m_body;
            if (this.vAttachment != null)
                message.Attachments.Add(this.vAttachment);
            emailClient.Send(message);
            retMsg = c_success;
        }
        catch (Exception ex)
        {
            retMsg = ex.Message.ToString();
        }
        return retMsg;
    }
    #endregion 

}
 
Share this answer
 
Comments
Naveen020190 1-Aug-13 23:49pm    
How to separate eamil , while emails are in multiple rows, please help me....
Alesha Mary Milred Fernandes 7-Sep-13 4:31am    
i did not get you.Please clarify your question?
XML
<appSettings> In the webconfig file add this
            <add key="to" value="cparole@imtsus.com"/>
    <add key ="to" value="druiz@imtsus.com"/>
    <add key ="to" value="rmiller@imtsus.com"/>
    <add key ="to" value="rdasan@imtsus.com"/>
            <add key="from" value="avilparackal@gmail.com"/>
            <add key="id" value="Ur gmail"/>
            <add key="pswd" value="Password""/>
            <add key="port" value="587"/>
            <add key="smtp" value="smtp.gmail.com"/>
      </appSettings>




XML
private void sendmail()
  {

      try
      {
    str_mailer.Append(@"<b>Name : </b>  " + txtsubject.Text);
             str_mailer.Append(@"\n\n\n\ <b>Email Address : </b>" + txtmessage.Text );
             str_mailer.Append(@"<br/><b>Phone No : </b>" + txtTo.Text);
             //str_mailer.Append(@"<br/><b>Type Of Service : </b>" + dd_select.Text );
             //str_mailer.Append(@"<br/><b>Estimated Budget : </b>" + dd_budget.Text);
             //str_mailer.Append(@"<br/>" + "<b>Comment : </b>" + txt_comment.Text );
             //str_mailer.Append(@"<br/>" + "<b>How Did You hear about Us : </b>" + txtget_id.Text);
             //below line m giving  sender's email address  and receiever's email address  that is also mentioned inside the <appSettings></appSettings> in the web.config file
             // and m also giving str_mailer.ToString() , in the str_mailer.ToString() coming  completed message with the html tags
             System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage(ConfigurationManager.AppSettings["id"], ConfigurationManager.AppSettings["to"], "Info", str_mailer.ToString());
             //below line m giving  sender's email address and password of that email that is mentioned inside the <appSettings></appSettings> in the web.config file
             System.Net.NetworkCredential mailAuthentication = new System.Net.NetworkCredential(ConfigurationManager.AppSettings["id"], ConfigurationManager.AppSettings["pswd"]);
             //below line m giving  smtp and port no: that is also mentioned inside the <appSettings></appSettings> in the web.config file
            System.Net.Mail.SmtpClient mailClient = new System.Net.Mail.SmtpClient(ConfigurationManager.AppSettings["smtp"], Convert.ToInt32(ConfigurationManager.AppSettings["port"]));
            //System.Net.Mail.SmtpClient mailClient = new System.Net.Mail.SmtpClient("smtp.gmail.com", 587);
            //below m setting some important properties that is necessary to send the email
            mailClient.EnableSsl = true;
            //below property IsBodyHtml in true because inside the stringbuilder am using some HTMl tags
            mail.IsBodyHtml = true;
            mailClient.UseDefaultCredentials = false;
            mailClient.Credentials = mailAuthentication;
            mailClient.Send(mail);
            // when all the process will be completed then a message will be displayed inside the label
            lbl_msg.Text = "Thank you, your mail has been sent successfully.";
        }


        catch
        {



                lbl_msg.Text = "Please wait..";
                sendmail();


        }

    }



    protected void btnsend_Click(object sender, EventArgs e)
    {
 sendmail();
    }
 
Share this answer
 
Hi...
Can u see this link.
How I can track Email send or Not Through Asp .Net?[^]
Thank u.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900