0

The following is a method for sending an Email from a Razor page in ASP.NET Core. I need to use MailKit since System.Net.Mail is not available in ASP.NET Core.

Despite much research, I haven't been able to figure out a way to include the image to the Email. Note that it doesn't have to be an attachment - embedding the image will work.

    public ActionResult Contribute([Bind("SubmitterScope, SubmitterLocation, SubmitterItem, SubmitterCategory, SubmitterEmail, SubmitterAcceptsTerms, SubmitterPicture")]
        EmailFormModel model)
    {

        if (ModelState.IsValid)
        {
            try
            {
                var emailName= _appSettings.EmailName;
                var emailAddress = _appSettings.EmailAddress;
                var emailPassword = _appSettings.EmailPassword;

                var message = new MimeMessage();
                message.From.Add(new MailboxAddress(emailName, emailAddress));
                message.To.Add(new MailboxAddress(emailName, emailAddress));
                message.Subject = "Record Submission From: " + model.SubmitterEmail.ToString();
                message.Body = new TextPart("plain")
                {
                    Text = "Scope: " + model.SubmitterScope.ToString() + "\n" +
                        "Zip Code: " + model.SubmitterLocation.ToString() + "\n" +
                        "Item Description: " + model.SubmitterItem.ToString() + "\n" +
                        "Category: " + model.SubmitterCategory + "\n" +
                        "Submitted By: " + model.SubmitterEmail + "\n" +
                        // This is the file that should be attached.
                        //"Picture: " + model.SubmitterPicture + "\n" +
                        "Terms Accepted: " + model.SubmitterAcceptsTerms + "\n"
                };

                using (var client = new SmtpClient())
                {
                    client.Connect("smtp.gmail.com", 587);

                    // Note: since we don't have an OAuth2 token, disable
                    // the XOAUTH2 authentication mechanism.
                    client.AuthenticationMechanisms.Remove("XOAUTH2");

                    // Note: only needed if the SMTP server requires authentication
                    client.Authenticate(emailAddress, emailPassword);

                    client.Send(message);
                    client.Disconnect(true);
                    return RedirectToAction("Success");
                }
            }
            catch (Exception ex)
            {

                Debug.WriteLine(ex.Message + ": " + ex.StackTrace);
                return RedirectToAction("Failure");
            }
        }
        else
        {
            return View();
        }
    }
Steve Land
  • 4,852
  • 2
  • 17
  • 36
C.H.
  • 367
  • 1
  • 3
  • 8
  • 1
    Possible duplicate of [MimeKit: How to embed images?](https://stackoverflow.com/questions/31406784/mimekit-how-to-embed-images) – Simon Fox Jul 16 '17 at 22:43
  • As @SimonFox noted, this question is a duplicate. One thing that you will have to do is switch from plain text to HTML because there is no way to "embed" an image into a plain text message body in the way that you seem to be trying to do it. – jstedfast Jul 19 '17 at 21:02
  • Doesn't work. My issue is that I am trying to let the USER upload an attachment. It seems that because of security restrictions in almost every modern browser, knowing the local file path is impossible. That's the problem I'm trying to work around. – C.H. Jul 20 '17 at 21:55
  • @C.H. so this question isn't about MailKit at all? it is about uploading an image with asp.net-core mvc? – Simon Fox Aug 14 '17 at 00:39
  • It's about sending an image in an Email with ASP.NET Core MVC, yes. – C.H. Aug 15 '17 at 21:28
  • @C.H. I would start by looking at the following to learn about uploading files using Core MVC https://learn.microsoft.com/en-us/aspnet/core/mvc/models/file-uploads essentially what you need to do is upload the files separately to sending the email. The file upload will store the images server side temporarily so that the action responsible for sending the email can actually get hold of them – Simon Fox Aug 15 '17 at 22:45
  • I'll check it out - thx @Simon Fox. – C.H. Aug 17 '17 at 20:07

1 Answers1

1

This is from the FAQ on Mailkit github repo, and seems to cover the full process. https://github.com/jstedfast/MailKit/blob/master/FAQ.md#CreateAttachments

var message = new MimeMessage ();
message.From.Add (new MailboxAddress ("Joey", "joey@friends.com"));
message.To.Add (new MailboxAddress ("Alice", "alice@wonderland.com"));
message.Subject = "How you doin?";

// create our message text, just like before (except don't set it as the message.Body)
var body = new TextPart ("plain") {
    Text = @"Hey Alice,

What are you up to this weekend? Monica is throwing one of her parties on
Saturday and I was hoping you could make it.

Will you be my +1?

-- Joey
"
};

// create an image attachment for the file located at path
var attachment = new MimePart ("image", "gif") {
    ContentObject = new ContentObject (File.OpenRead (path), ContentEncoding.Default),
    ContentDisposition = new ContentDisposition (ContentDisposition.Attachment),
    ContentTransferEncoding = ContentEncoding.Base64,
    FileName = Path.GetFileName (path)
};

// now create the multipart/mixed container to hold the message text and the
// image attachment
var multipart = new Multipart ("mixed");
multipart.Add (body);
multipart.Add (attachment);

// now set the multipart/mixed as the message body
message.Body = multipart;
Steve Land
  • 4,852
  • 2
  • 17
  • 36
  • I tried this. It does *not* work with a Web app where a user is uploading a file from a local file path because the local file path is not known. – C.H. Jul 20 '17 at 21:53
  • 1
    This code executes on the server - not in the browser. To use a file from the users computer you will have to upload it to the server first. See this [question](https://stackoverflow.com/questions/15680629/mvc-4-razor-file-upload) – Steve Land Jul 21 '17 at 09:34
  • Got it - will play around with the code in the linked post. Thx. – C.H. Jul 24 '17 at 21:37