Sunday, September 19, 2010

Send Email With Attachment in asp.net

Send Email Using Gmail in ASP.NET

If you want to send email using your Gmail account or using Gmail's smtp server in ASP.NET application or if you don't have a working smtp server to send mails using your ASP.NET application or aspx page than sending e-mail using Gmail is best option.

you need to write code like this

First of all add below mentioned namespace in code behind of aspx page from which you want to send the mail.

using System.Net.Mail;

Now write this code in click event of button

C# code

protected void Button1_Click(object sender, EventArgs e)
{
  MailMessage mail = new MailMessage();
  mail.To.Add("jainamit.agra@gmail.com");
  mail.To.Add("amit_jain_online@yahoo.com");
  mail.From = new MailAddress("jainamit.agra@gmail.com");
  mail.Subject = "Email using Gmail";

  string Body = "Hi, this mail is to test sending mail"+ 
                "using Gmail in ASP.NET";
  mail.Body = Body;

  mail.IsBodyHtml = true;
  SmtpClient smtp = new SmtpClient();
  smtp.Host = "smtp.gmail.com"; //Or Your SMTP Server Address
  smtp.Credentials = new System.Net.NetworkCredential
       ("YourUserName@gmail.com","YourGmailPassword");
//Or your Smtp Email ID and Password
  smtp.EnableSsl = true;
  smtp.Send(mail);
}

VB.NET code

Imports System.Net.Mail
 
Protected  Sub Button1_Click
(ByVal sender As Object, ByVal e As EventArgs)
  Dim mail As MailMessage =  New MailMessage() 
  mail.To.Add("jainamit.agra@gmail.com")
  mail.To.Add("amit_jain_online@yahoo.com")
  mail.From = New MailAddress("jainamit.agra@gmail.com")
  mail.Subject = "Email using Gmail"
 
  String Body = "Hi, this mail is to test sending mail"+ 
                "using Gmail in ASP.NET"
  mail.Body = Body
 
  mail.IsBodyHtml = True
  Dim smtp As SmtpClient =  New SmtpClient() 
  smtp.Host = "smtp.gmail.com" //Or Your SMTP Server Address
  smtp.Credentials = New System.Net.NetworkCredential
       ("YourUserName@gmail.com","YourGmailPassword")
  smtp.EnableSsl = True
  smtp.Send(mail)
End Sub


You also need to enable POP by going to settings > Forwarding and POP in your gmail account

Change YourUserName@gmail.com to your gmail ID and YourGmailPassword to Your password for Gmail account and test the code.

If your are getting error mentioned below
"The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required."

than you need to check your Gmail username and password.

If you are behind proxy Server then you need to write below mentioned code in your web.config file
<system.net>
<defaultProxy>
<proxy proxyaddress="YourProxyIpAddress"/>
</defaultProxy>
</system.net>

If you are still having problems them try changing port number to 587
smtp.Host = "smtp.gmail.com,587";

If you still having problems then try changing code as mentioned below
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.UseDefaultCredentials = False;
smtp.Credentials = new System.Net.NetworkCredential
("YourUserName@gmail.com","YourGmailPassword");
smtp.EnableSsl = true;
smtp.Send(mail);

In this example i am going to describe how to send email with attachment in ASP.NET using fileUpload Control.
I am saving the uploaded file into memory stream rather then saving it on server.

And for this example i m using Gmail SMTP server to send mail, this code also works fine with any SMTP Server.

For sending Email in ASP.NET , first of all we need to add Syatem.Net.Mail namespace in code behind of aspx page. 

In my previous article i describe how to send mail using gmail in asp.net 





Create the page as shown in the image above, put textbox for message and FileUpload Control for adding the file attachment.

Write below mentioned code in click event of Send button in Code behind of page

C# Code Behind
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Net.Mail;

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnSend_Click(object sender, EventArgs e)
    {
        MailMessage mail = new MailMessage();
        mail.To.Add(txtTo.Text);
        //mail.To.Add("amit_jain_online@yahoo.com");
        mail.From = new MailAddress(txtFrom.Text);
        mail.Subject = txtSubject.Text;
        mail.Body = txtMessage.Text;
        mail.IsBodyHtml = true;

        //Attach file using FileUpload Control and put the file in memory stream
        if (FileUpload1.HasFile)
        {
            mail.Attachments.Add(new Attachment(FileUpload1.PostedFile.InputStream, FileUpload1.FileName));
        }
        SmtpClient smtp = new SmtpClient();
        smtp.Host = "smtp.gmail.com"; //Or Your SMTP Server Address
        smtp.Credentials = new System.Net.NetworkCredential
             ("YourGmailID@gmail.com", "YourGmailPassword");
        //Or your Smtp Email ID and Password
        smtp.EnableSsl = true;
        smtp.Send(mail);

    }
}



VB.NET Code Behind
Imports System
Imports System.Data
Imports System.Configuration
Imports System.Web
Imports System.Web.Security
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts
Imports System.Web.UI.HtmlControls
Imports System.Net.Mail

Public Partial Class _Default
    Inherits System.Web.UI.Page
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
        
    End Sub
    Protected Sub btnSend_Click(ByVal sender As Object, ByVal e As EventArgs)
        Dim mail As New MailMessage()
        mail.[To].Add(txtTo.Text)
        'mail.To.Add("amit_jain_online@yahoo.com");
        mail.From = New MailAddress(txtFrom.Text)
        mail.Subject = txtSubject.Text
        mail.Body = txtMessage.Text
        mail.IsBodyHtml = True
        
        'Attach file using FileUpload Control and put the file in memory stream
        If FileUpload1.HasFile Then
            mail.Attachments.Add(New Attachment(FileUpload1.PostedFile.InputStream, FileUpload1.FileName))
        End If
        Dim smtp As New SmtpClient()
        smtp.Host = "smtp.gmail.com"
        'Or Your SMTP Server Address
        smtp.Credentials = New System.Net.NetworkCredential("YourGmailID@gmail.com", "YourGmailPassword")
        'Or your Smtp Email ID and Password
        smtp.EnableSsl = True
            
        smtp.Send(mail)
    End Sub
End Class
Build and run the application to test the code

Hope this helps