Tuesday, August 7, 2012

take screenshot and send email using C# .net

// usings

using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Net.Mime;
using System.Windows.Forms;
using System.Net.Mail;
using System.Net;

// fill in the apt content
// FILE_PATH can be a temp path with temp name with jpg extention   
// message configuration


        private string RECIPIENT = "xxxx@gmail.com";
         private string MAIL_SUBJECT = "[xxx]";
        private string MAIL_BODY = "x.";
      
//smtp client configuration
        private string SMTP_CLIENT = "smtp.gmail.com";
        private int SMTP_PORT = 587;
        private string USERNAME = "xxxxxx@gmail.com";
        private string PASSWORD = "xxxxx";
public string Pns()
        {
            string path = string.Empty;
            try
            {
              
            //print the screen
            Bitmap printscreen = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
              Graphics graphics = Graphics.FromImage(printscreen as Image);  
            graphics.CopyFromScreen(0000, printscreen.Size);
              path = FILE_PATH;
            printscreen.Save(path, ImageFormat.Jpeg );
          
            //Send the mail with attachment
            MailMessage mm = new MailMessage();
            mm.From = new MailAddress(USERNAME);
            mm.To.Add(RECIPIENT);
          
            mm.Subject = MAIL_SUBJECT ;
            mm.Body = MAIL_BODY;
       
            mm.IsBodyHtml  = true;
          
            Attachment att = new Attachment(path,MediaTypeNames.Image.Jpeg);
            mm.Attachments.Add(att);
          
            sendEmail(mm);
          
            mm.Dispose();
            }
            catch (Exception ex)
            {
                throw ex;
            }
                                 
            return path;
        }
      
        private void sendEmail(MailMessage mm)
        {
            var client = new SmtpClient(SMTP_CLIENT, SMTP_PORT)
            {
                Credentials = new NetworkCredential(USERNAME, PASSWORD ),
                EnableSsl = true
            };
            client.Send(mm);
          
            client.Dispose();
        }