开发者

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");

                开发者_StackOverflowclient.Credentials = CredentialCache.DefaultNetworkCredentials;

                client.Send(message);
            }

Thanks!


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);


If you dont want your app to hang while this may take some time (if the image is big, or the servers are unresponsive, you need to put it into a separate thread. (Many examples already exist)

As a few of us have also pointed out, you need to also send the Email, your code above doesnt do that. Be aware of course that if gmail thinks you're trying to relay through them, the mail probably wont send.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜