Sunday, 21 July 2013

Embed mail with Gmail

Aspx Page
----------
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="EmbedMail.aspx.cs" Inherits="EmbedMail" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Button ID="SendMail" runat="server" Text="Send Mail"
            onclick="SendMail_Click" />
    </div>
    </form>
</body>
</html>

CS Page
-------
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections.Specialized;
using System.Net.Mail;
using System.Text;
using System.IO;

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

    }
    protected void SendMail_Click(object sender, EventArgs e)
    {
        SendHTMLMail();
    }

    // Method Which is used to Get HTML File and replace HTML File values with dynamic values and send mail
    public void SendHTMLMail()
    {
        //StreamReader reader = new StreamReader(Server.MapPath("~/top.html"));
        StreamReader reader = new StreamReader(Server.MapPath("~/MailContent.aspx"));
        string readFile = reader.ReadToEnd();
        string myString = "";
        myString = readFile;
    
        MailMessage Msg = new MailMessage();
       // MailAddress fromMail = new MailAddress("");
        // Sender e-mail address.
        Msg.From = fromMail;
        // Recipient e-mail address.
        Msg.To.Add(new MailAddress("To email id"));
        // Subject of e-mail
        Msg.Subject = "Send Mail with HTML File";
        Msg.Body = myString.ToString();
        Msg.IsBodyHtml = true;
        string sSmtpServer = "";
       
        sSmtpServer = "smtp.gmail.com";

        SmtpClient a = new SmtpClient();
        a.Host = sSmtpServer;
        a.Port = 587;
        a.Credentials = new System.Net.NetworkCredential("Your gmail id", "Your Password");
        a.EnableSsl = true;
        a.Send(Msg);
        reader.Dispose();
    }
}