Thursday, 12 April 2012

SEND AN EMAIL WITH ATTACHMENT USING C#

I have described an example to send an email using ASP.NET in C# and using GMAIL as a port.The Namespaces to be used are System.Net.Mail and System.IO. The code is written in the way that the attachment is stored in a folder temporarily before sending it and will be deleted afterwards.

  
 





In ASPX Page,

<table cellpadding="5" cellspacing="0" border="0">
  <tr>
    <td>To</td>
    <td>:</td>
    <td>
      <asp:TextBox ID="ToTextBox" runat="server" Width="400px"></asp:TextBox>
    </td>
  </tr>
  <tr>
    <td>Cc</td>
    <td>:</td>
    <td><asp:TextBox ID="CcTextBox" runat="server" Width="400px"></asp:TextBox></td>
  </tr>
  <tr>
    <td>Subject</td>
    <td>:</td>
    <td><asp:TextBox ID="SubjectTextBox" runat="server" Width="400px"></asp:TextBox></td>
  </tr>
  <tr>
    <td>Attachments</td>
    <td>:</td>
    <td>
    <asp:FileUpload ID="FileUpload" runat="server" Width="400px" />
    </td>
  </tr>
  <tr>
    <td valign="top">Message</td>
    <td valign="top">:</td>
    <td>
<asp:TextBox ID="MessageTextBox" runat="server" TextMode="MultiLine" Columns="20"   Rows="10" Width="400px"></asp:TextBox></td>
  </tr>
  <tr>
    <td colspan="4" align="right">
    <asp:Button ID="SendButton" runat="server" Text="Send"
     onclick="SendButton_Click" /></td>
  </tr>
</table>
<div>
    <asp:Label ID="StatusLabel" runat="server" Text="" ForeColor="Green" Font-Size="Large" Visible="false"></asp:Label>
</div>
                
In ASPX.CS Page,



    protected void SendButton_Click(object sender, EventArgs e)
    {
        this.StatusLabel.Visible = true;
        string FileName = string.Empty;
        MailMessage objMail = new MailMessage();
        objMail.From = new MailAddress("Your Mail Address");
        objMail.To.Add(new MailAddress(ToTextBox.Text.Trim()));
        if (CcTextBox.Text != string.Empty)
        {
            objMail.CC.Add(new MailAddress(CcTextBox.Text.Trim()));
        }
        objMail.Subject = SubjectTextBox.Text.Trim();
        objMail.Body = MessageTextBox.Text.Trim();
        objMail.IsBodyHtml = true;
        try
        {
            if (FileUpload.HasFile)
            {
                HttpPostedFile pf = this.FileUpload.PostedFile;
                // Filepath in which the file has to be stored
                FileName = Server.MapPath("~") + @"\uploads\" + FileUpload.FileName.Substring(FileUpload.FileName.LastIndexOf('\\') + 1);
                if (pf.ContentLength > 0)
                {
                    pf.SaveAs(FileName);
                    pf.InputStream.Flush();
                    pf.InputStream.Close(); // just in case any other process has the handle
                }
                pf.InputStream.Dispose();
                Attachment attach = new Attachment(FileName);
                objMail.Attachments.Add(attach);
            }
        SmtpClient client = new SmtpClient();
        client.Credentials = new System.Net.NetworkCredential("Mail Address", "Password");
        client.Port = 587; // Gmail works on this port
        client.Host = "smtp.gmail.com";
        client.EnableSsl = true; //Gmail works on SSL
        client.Send(objMail);
       
        objMail.Dispose();
        client.Dispose();
        if (FileUpload.HasFile)
        {
            File.Delete(FileName);
        }
       
        }
        catch (SmtpFailedRecipientsException exp)
        {
            StatusLabel.Text = "Unable to send email to " + exp.FailedRecipient;
        }
        catch (SmtpFailedRecipientException exp)
        {
            StatusLabel.Text = "Unable to send email to " + exp.FailedRecipient + "<br />Error Message: " + exp.Message.Replace("'", "\'");
        }
        catch (SmtpException exp)
        {
            StatusLabel.Text = "There was a problem in sending the email to " + ToTextBox.Text.Trim() + "<br />" + exp.Message.Replace("'", "\'");
        }
        catch (Exception exp)
        {
            StatusLabel.Text = "There was an Unknown Problem in sending the email:<br />"
                            + exp.Message.Replace("'", "\'");
        }

        if (StatusLabel.Text == string.Empty)
        {
            StatusLabel.Text = "Mail sent successfully";
            ToTextBox.Text = string.Empty;
            CcTextBox.Text = string.Empty;
            SubjectTextBox.Text = string.Empty;
            MessageTextBox.Text = string.Empty;
        }
    }      














               
























1 comment:

  1. Hello,

    Your style of blog presentation is very attractive. This is very interesting post. E-mail allows you to communicate quickly anywhere in the world, providing your recipient has an e-mail account. I am really thankful to you for providing this unique information....

    ReplyDelete