Dynamic Web TWAIN: How to email an uploaded image using C#

When you upload an image, you might want to email the image to a client too. Using "System.Net.Mail", we can achieve this easily. We will use Gmail as an example here.

Assume you have the below lines in your action page (C#) for saving the uploaded image:

HttpFileCollection files = HttpContext.Current.Request.Files;
HttpPostedFile uploadfile = files["RemoteFile"];
uploadfile.SaveAs(System.Web.HttpContext.Current.Request.MapPath(".") + "/ImageScanned/" + uploadfile.FileName);

Now let's add code to email the same image.

First of all, we need to use the namespace "System.Net.Mail":

using System.Net.Mail;

Then, in Web.config, add the configuration for Gmail Server:

‹system.net›
    ‹mailSettings›
      ‹smtp from="***@gmail.com"›
        ‹network host="smtp.gmail.com" port="25" userName="***@gmail.com" password="***" enableSsl="true"/›
      ‹/smtp›
    ‹/mailSettings›
  ‹/system.net›

Lastly, here is the code for sending the image as an attachment:

SmtpClient client = new SmtpClient();
MailAddress from = new MailAddress("***@gmail.com", " Test", System.Text.Encoding.UTF8);
MailAddress to = new MailAddress("***@gmail.com");
MailMessage message = new MailMessage(from, to);
message.Body = "This is a test email sent by ASP.NET";
message.BodyEncoding = System.Text.Encoding.UTF8;
message.Subject = "Just Testing";
message.SubjectEncoding = System.Text.Encoding.UTF8;
// Create the file attachment
Attachment data = new Attachment(uploadfile.InputStream, uploadfile.FileName);
message.Attachments.Add(data);
client.Send(message);
data.Dispose();
Is this page helpful?

Leave a Reply

Your email address will not be published.