Wednesday 5 June 2013

Send Mail in Asp.net,C# using Gmail/Yahoo

First method

MailMessage _MailMsg = new MailMessage();

 _MailMsg.From = new MailAddress(FromEmail);
_MailMsg.To.Add(EmailId);
_MailMsg.Subject = Subject;
  _MailMsg.Body = Body;
 _MailMsg.Priority = System.Net.Mail.MailPriority.High;
  _MailMsg.IsBodyHtml = true;
           
  _MailMsg.Attachments.Add(new Attachment(FileAttachment));

                SmtpClient mailSender = new SmtpClient();
                mailSender.Host = SMTP_Host;

                //mailSender.Credentials = new System.Net.NetworkCredential(FromEmail, Password);
                mailSender.Port = 578;//--- used for abc@gmail.com
                mailSender.EnableSsl = true;
                mailSender.Credentials = new System.Net.NetworkCredential(FromEmail, Password);
                mailSender.Timeout = 200000;
                mailSender.Send(_MailMsg);

Second Method

 Codebehnd: .CS


protected void btnsend_Click(object sender, EventArgs e)
    {
        string from = "test@123@yahoo.in"; //Replace this with your own correct Gmail Address

        string to = txtmail.Text; //Replace this with the Email Address to whom you want to send the mail
        MailMessage mail = new MailMessage();
        mail.To.Add(to);
        mail.From = new MailAddress(from, "Harish", System.Text.Encoding.UTF8);
        mail.Subject = txtsub.Text;
        mail.SubjectEncoding = System.Text.Encoding.UTF8;
        mail.Body = "your body msg";
        mail.BodyEncoding = System.Text.Encoding.UTF8;
        mail.IsBodyHtml = true;
        mail.Priority = MailPriority.High;
        

        SmtpClient client = new SmtpClient();
        //Add the Creddentials- use your own email id and password

        client.Credentials = new System.Net.NetworkCredential(from, "password");
        client.Port = 587; // Gmail works on this port 
       // client.Port=465; //YahooMail on this port
       
        client.Host = "smtp.gmail.com";
        //client.Host = "plus.smtp.mail.yahoo.com";//Yahoomail works on this Host Name
        client.EnableSsl = true; //Gmail works on Server Secured Layer
        try
        {
            client.Send(mail);
        }
        catch (Exception ex)
        {
            Exception ex2 = ex;
            string errorMessage = string.Empty;
            while (ex2 != null)
            {
                errorMessage += ex2.ToString();
                ex2 = ex2.InnerException;
            }
            lblmessege.Text = errorMessage;
            
        }
        finally
        {
            lblmessege.Visible = true;
            lblmessege.Text = txtname.Text+  " : Your Messege Submitted";
                       

        }


No comments:

Post a Comment