Showing posts with label Mail. Show all posts
Showing posts with label Mail. Show all posts

Tuesday, 29 April 2014

Send Mail with Attachment in asp.net

 MailAddress SendFrom = new MailAddress("brijesh.singh879@gmail.com", "Brijesh");
        MailAddress SendTo = new MailAddress("brijesh.singh879@gmail.com");
        System.Net.Mail.MailMessage MyMessage = new System.Net.Mail.MailMessage(SendFrom, SendTo);
        MyMessage.IsBodyHtml = true;
        MyMessage.Subject = "Send Mail with attachment ";
        MyMessage.Body = "Body";
        if (fupResume.HasFile)
        {
            string FileName = Path.GetFileName(fupResume.PostedFile.FileName);
            MyMessage.Attachments.Add(new Attachment(fupResume.PostedFile.InputStream, FileName));
        }
        System.Net.NetworkCredential authentication = new System.Net.NetworkCredential("brijesh.singh879@gmail.com", "password");
        SmtpClient client = new SmtpClient("smtp.gmail.com", 25);//587
        client.EnableSsl = true;
        client.UseDefaultCredentials = true;
        client.Credentials = authentication;
        client.Send(MyMessage);

Tuesday, 8 October 2013

ASP.NET - Export Gridview data to excel and directly send a mail with exported excel file

On Control Event use this code in C#:

                        GridView gdvExportxls = new GridView();
                        gdvExportxls.DataSource = dtnew;
                        gdvExportxls.DataBind();
                        MemoryStream ms = new MemoryStream();
                        System.IO.StringWriter stringWriter = new System.IO.StringWriter();
                        System.Web.UI.HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter);
                        gdvExportxls.RenderControl(htmlWriter);
                        byte[] excelFile = System.Text.Encoding.ASCII.GetBytes(stringWriter.ToString());
                        ms.Write(excelFile, 0, excelFile.Length);
                        ms.Position = 0;

                        Attachment attachment = new Attachment(ms, "Test.xls", "application/vnd.xls");
                        SendMail(attachment);


          private void SendMail(Attachment excel)
        {
            MailMessage mail = new MailMessage();
            SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
            mail.From = new MailAddress("brijesh.singh879@gmail.com")
            mail.Subject = "Export GridView to Excel";
            mail.Body = "mail with attachment";

            //System.Net.Mail.Attachment attachment;
            //attachment = excel;
            mail.Attachments.Add(excel);

            SmtpServer.Port = 587;
            SmtpServer.Credentials = new System.Net.NetworkCredential("brijesh.singh879@gmail.com", "*******");
            SmtpServer.EnableSsl = true;
            SmtpServer.Send(mail);

        }