Wednesday 27 June 2012

How to send mail from web application with Attachment

How to send mail from web application with Attachment
      
 This sample code snippet works for sending mails from ur id via web application. Integrate this code and check out how this works

( using System.Net;
using System.Net.Mail;) This two are the important directive needed for this code snippet



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.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;
using System.Net;
using System.Net.Mail;


namespace crjsptry
{
    public partial class WebForm13 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            txtTo.Text = "admin@gmail.com";
        }
        protected void Button2_Click(object sender, EventArgs e)
        {
            MailMessage msg = new MailMessage();
            msg.From = new MailAddress(txtGaddress.Text, "Sender's Name");
            msg.To.Add(new MailAddress(txtTo.Text));
            msg.Subject = txtSub.Text;
            msg.Body = TextBox1.Text;
            msg.IsBodyHtml = true;
            if (FileUpload1.HasFile)
            {
                msg.Attachments.Add(new Attachment(FileUpload1.PostedFile.InputStream, FileUpload1.FileName));
            }
            SmtpClient smtp = new SmtpClient();
            smtp.Host = "smtp.gmail.com";
            smtp.Credentials = new NetworkCredential(txtGaddress.Text, txtGpass.Text);
            lblResult.Visible = true;
            smtp.EnableSsl = true;
            try
            {
                smtp.Send(msg);
                //lblResult.Text = "sent successfully";
                    Response.Redirect("donesuccessfully.aspx");
            }
            catch (Exception ex)
            {
                lblResult.Text = "Failed";
            }


        }


        protected void txtTo_TextChanged(object sender, EventArgs e)
        {


        }
    }
}

No comments:

Post a Comment