Thursday, February 6, 2020

EMAIL WITH C#

private void sendMail()
    {
        MailMessage msg = new MailMessage();
        string ToMail = "*******@gmail.com";
        try
        {
            msg.From = new MailAddress("*****@gmail.com");

            string[] multi=ToMail.Split(',');

            foreach (string mailTo in multi)
            {
                msg.To.Add(mailTo);
            }
           
            msg.Body = "Residential Property Details. </br> </br>Please Verify from the department!!. <br> Thank You.";
            msg.Attachments.Add(new Attachment(pdfFile));
            msg.Attachments.Add(new Attachment(pdfFile1));
            msg.IsBodyHtml = true;
            msg.Subject = "Property Details As On : " + DateTime.Now.ToString() + " date";
            SmtpClient smt = new SmtpClient("smtp.gmail.com");
            smt.Port = 587;
            smt.Credentials = new NetworkCredential("*****@gmail.com", "PASS***");
            smt.EnableSsl = true;
            smt.Send(msg);
            //string script = "<script>alert('Mail Sent Successfully')</script>";
            //ClientScript.RegisterStartupScript(this.GetType(), "mailSent", script);
            ClientScript.RegisterStartupScript(typeof(Page), "closePage", "window.open('close.htm', '_self', null);", true);
        }
        catch (Exception ex)
        {
        }
        finally
        {
            /*
                so that the error "The process cannot access the file because it is being used by another process" should not occur when we immediately
                try to send another mail after one has been sent.
                w3wp.exe:5800 CREATE D:\\Testcrystal.pdf
                w3wp.exe:5800 WRITE D:\\Testcrystal.pdf
                w3wp.exe:5800 CLOSE D:\\Testcrystal.pdf
                w3wp.exe:5800 OPEN D:\\Testcrystal.pdf
                w3wp.exe:5800 READ D:\\Testcrystal.pdf
                As you can see, it created the PDF, it wrote the PDF, it closed the PDF (expected).
                Then, there was an unexpected Open, Read, without close immediately after the file was created. So that's why we've to close the file after
sending
             * it through mail because msg will open and read the file but the file is not close automattically after sending it. There will no error while sending
the first
             * mail but when you try to send the next mail one after the other the above error will rise. to avoid this error we are using the Dispose methods
to release
             * all the resources which are being used.
            */
            msg.Dispose();
        }
    }

No comments:

Post a Comment

Ad hoc queries

 select max(cast(convert(varchar, convert(datetime, [CR_DATE], 103), 101) as date))  from OPENDATASOURCE (        'SQLNCLI'         ...