Search code examples
c#.netsmtpclient

how to send an email with an attachment from C#?


I'm trying to write a code, what would save the content of a picturebox ( works ) and email it ( doesn't work ).

What do you think might be the problem? Should there be anything more to the SmtpClient client = new SmtpClient("smtp.gmail.com"); ?

Also the program shouldn't freeze up while the image gets uploaded, rather then, if necessary, be able to simultaneously upload a few images.

            System.Drawing.Image img = pictureBox1.Image;
            string name = "" + DateTime.Now.ToString("dd_MM_yyyy_HH_mm_ss") + ".jpg";
            img.Save(name, System.Drawing.Imaging.ImageFormat.Jpeg);

            if (chb_notif.Checked == true) ////////////// SEND EMAIL!
            {

                MailMessage message = new MailMessage(
                   "do-not-reply@123.com",
                   tb_email.Text ,
                   "VIDEO FENCE",
                   "Your perimeter has been breeched! System name: " + Environment.MachineName + "." );

                Attachment data = new Attachment(name);

                ContentDisposition disposition = data.ContentDisposition;
                disposition.CreationDate = System.IO.File.GetCreationTime(name);
                disposition.ModificationDate = System.IO.File.GetLastWriteTime(name);
                disposition.ReadDate = System.IO.File.GetLastAccessTime(name);

                message.Attachments.Add(data);

                //Send the message.
                SmtpClient client = new SmtpClient("smtp.gmail.com");

                client.Credentials = CredentialCache.DefaultNetworkCredentials;

                client.Send(message);
            }

Thanks!


Solution

  • for:

    "The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required"

    Try use:

     var client = new SmtpClient("smtp.gmail.com", 587)
            {
                Credentials = new NetworkCredential("username", "password"),
                EnableSsl =true
            };
    
            client.Send(message);