Mohammed
Mohammed

Reputation: 7

Sending email with attachment in ASP.NET C# web Application

I am having a web application with contact us page in that i am having field like Name: email address: phone number : Attach file : Message: Send button

Now on send button click, i want to send the email to some [email protected] with the above body content.

to do some what code i need to write in .cs file

this is what i have tried

protected void Button_Click(object sender, EventArgs e)
{
    try
    {
        if (Page.IsValid)
        {
            MailMessage mail = new MailMessage();
            SmtpClient smtpServer = new SmtpClient("smtp.gmail.com");

            mail.From = new MailAddress("[email protected]");
            mail.To.Add("[email protected]");

            mail.Body = "<b> Sender Name : </b>" + txtbname.Text + "<br/>"
                + "<b> Sender Email : </b>" + txtbemail.Text + "<br/>"
                + "<b> Sender Contact Number : </b>" + txtphone.Text + "<br/>"
                + "<b> Message : </b>" + txtbmessage.Text;

            System.Net.Mail.Attachment attachment;

            attachment = new System.Net.Mail.Attachment("Attachment" + this.fp);

            mail.Attachments.Add(attachment);

            mail.IsBodyHtml = true;


            smtpServer.Port = 587;
            smtpServer.Credentials = new System.Net.NetworkCredential("[email protected]", "password");

            smtpServer.EnableSsl = true;

            smtpServer.Send(mail);

            label1.ForeColor = System.Drawing.Color.Green;
            label1.Text = "SENT";
        }
    }
    catch (Exception ex)
    {
        label1.ForeColor = System.Drawing.Color.Red;
        label1.Text = "Failed";
    }
}

Upvotes: 0

Views: 640

Answers (1)

Midhun Mundayadan
Midhun Mundayadan

Reputation: 3182

For sending mail you have to Allow less secure apps from your gmail account

  1. Login with your gmail account and find "Allow less secure apps:" from here.

  2. Google manages security with your gmail account. You need to turn on "Allow less secure apps:" and you will receive mail in your gmail account.

Upvotes: 2

Related Questions