0

I have a program on the server that creates pdf sql reports and I need to have them so users can email them out. First off before everything gets automated I want them to be able to view the email and adjust it as needed.

Im been using office.interop.outlook but now that isn’t working on the server as people have told me earlier. To view the documents I put all the selected PDF reports in a .zip file and the user downloads the zip. Now I was thinking of doing the same thing for emails.

Creating a .zip file that contains emails with the pdf reports as the attachment. How could I create am email draft with an attachment the user could download and open on their own machine? I can successfully create a text file and download it. When I try to use Office.Interop.Outlook I cannot create the ‘MailItem’ and convert it to a byte array to put it in return File(). What would you suggest? Locally everything works perfectly.

I also read online about creating an .eml file and people cam open this as if it were and email. Everyone has Outlook in the company. Outlook has .msg files for its email.

Heres some stuff ive tried

 public ActionResult Testtxt()
    {
        var data = "Here is a string with information in it";
        var byteArray = System.Text.Encoding.ASCII.GetBytes(data);
        var memorystream = new MemoryStream(byteArray);
        return File(memorystream, "text/plain", "txtname.txt");
    }
    public void OutlookTest() // Errors when creating the email (permission rights)
    {
        ServiceResponse servRespObj = new ServiceResponse();
        //string downloadsPath = new KnownFolder(KnownFolderType.Downloads).Path;
        /// Test Mail on Server     /* mail draft = Untitled.msg */
        /// "application/vsd.ms-outlook" as MIME type.
        /// ".msg" as extension
        /// 1. FilePath, 2. ContentType(MIME), 3.FileName   return File(1,2,3); top=FileResult
        OutlookApp outlookapp = new OutlookApp();
        MailItem mailItem = outlookapp.CreateItem(OlItemType.olMailItem);
        mailItem.Subject = "This is a TEST msg - Subject02";
        mailItem.Body = "msg body02";
        //byte[] fileByteArray = System.IO.File.ReadAllBytes(mailItem);
        var byteArray = System.Text.Encoding.ASCII.GetBytes(mailItem);
        //return File(mailItem, "application/vsd.ms-outlook", "testMessage.msg");
        //mailItem.SaveAs(downloadsPath, OlSaveAsType.olMSG);
        //mailItem.Save();
    }
    public ActionResult EmailDraft2()
    {
        byte[] fileByteArray = null;
        string timeNow = DateTime.Now.ToString("MM-dd-yyyy-HHmmss");
        OutlookApp application = new OutlookApp();
        MailItem mailItem = application.CreateItem(OlItemType.olMailItem);
        mailItem.Subject = "test subject draft";
        mailItem.Body = "test body draft";

        using(MemoryStream stream = new MemoryStream())
        {
            /// Creates the .zip file.
            using(ZipArchive archive = new ZipArchive(stream, ZipArchiveMode.Create, true))
            {
                /// Iterates through the files
                //foreach
                /// Creates an archive for the .zip                     // & extension
                ZipArchiveEntry archiveEntry = archive.CreateEntry("filename" + ".msg");
                /// Adds the archive to the .zip
                //using(MemoryStream fileStream = new MemoryStream(mailItem.))
            }
        }

        return null;
    }
    public ActionResult CreateEMLemail()
    {
        string senderEmail = "Test@test.test.test";

        var mailMessage = new MailMessage();
        mailMessage.From = new MailAddress(senderEmail);
        mailMessage.To.Add("To_EmailSend@msn.com");
        mailMessage.Subject = "EML TEST MAIL SUBJECT";
        mailMessage.Body = "EML TEST MAIL BODY";

        var stream = new MemoryStream();
        ToEMLstream(mailMessage, stream, senderEmail);

        stream.Position = 0;
        return File(stream, "message/rfc822", "emlTESTmessage.eml");
    }
    private void ToEMLstream(MailMessage msg, Stream stream, string fromSender)
    {
        using(var client = new SmtpClient())
        {
            var id = 0;
            //var tempFolder = Path.Combine(Path.GetTempPath(), Assembly.GetExecutingAssembly().GetName().Name);
            //tempFolder = Path.Combine(tempFolder, "EMLtempFolder");
            var downloads = new KnownFolder(KnownFolderType.Downloads).Path;
            string timeNow = DateTime.Now.ToString("MM-dd-yyyy-HHmmss");
            var newFolder = Path.Combine(downloads, timeNow);
            //if (!Directory.Exists(tempFolder))
            if (!Directory.Exists(newFolder))
            {
                //Directory.CreateDirectory(tempFolder);
                Directory.CreateDirectory(newFolder);
            }
            //client.UseDefaultCredentials = true;
            //client.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory;
            //client.PickupDirectoryLocation = tempFolder;
            //client.Send(msg);

            //string newFile = Path.Combine(tempFolder, "emlTestmail.eml");
            string newFile = Path.Combine(newFolder, "emlTestmail.eml");
            //using (var streamr = new StreamReader(tempFolder))
            using (var streamr = new StreamReader(newFolder))
            {
                using (var streamw = new StreamWriter(newFile))
                {
                    string line;
                    while((line = streamr.ReadLine()) != null)
                    {
                        if(!line.StartsWith("X-Sender:") && !line.StartsWith("From:") &&
                            !line.StartsWith("X-Receiver: " + fromSender) &&
                            !line.StartsWith("To: " + fromSender))
                        {
                            streamw.WriteLine(line);
                        }
                    }
                }
            }
            {
                using(var filesteam = new FileStream(newFile, FileMode.OpenOrCreate))
                {
                    filesteam.CopyTo(stream);
                }
            }
        }
    }
Bigbear
  • 489
  • 2
  • 5
  • 21
  • 1
    I would highly suggest you use something like [System.Net.Mail.MailMessage](https://learn.microsoft.com/en-us/dotnet/api/system.net.mail.mailmessage?view=netframework-4.8) to send email instead of using Office.Interop.Outlook. I don't see a reason to use the Interop just to send email, unless you need any of Outlook features. – the_lotus Jan 20 '20 at 16:20
  • I would just want the server to create the email draft and save it to the network or have the user download it to their local machine, I have been trying to get System.Net.Mail; to create a mailmessage of type .eml but I haven't got it working yet. still trying. – Bigbear Jan 20 '20 at 18:34
  • my mistake, I thought you wanted to send the email. But you want to save some sort of email template that the user can open. – the_lotus Jan 20 '20 at 19:34
  • yeah. im still trying to get the server to create the email and save it to a folder. no luck yet but i know im close – Bigbear Jan 20 '20 at 21:08
  • Maybe this post responds to your need [https://stackoverflow.com/questions/1264672/how-to-save-mailmessage-object-to-disk-as-eml-or-msg-file](https://stackoverflow.com/questions/1264672/how-to-save-mailmessage-object-to-disk-as-eml-or-msg-file) – Barax Jan 21 '20 at 11:23

1 Answers1

0

I got it working!

I can create an email as an .eml mail message. Attach a report to it and save the new email to the server.

Thank you all for all the help! Here is what I used.

 $("#btnEmailTest").on("click", function () {
            $.ajax({
                type: "POST",
                url: '@Url.Action("Testemail2", "Service")',
                contentType: "application/json",
                success: function (data) {
                    //window.location
                    alert("success : " + data);
                },
                error: function (xhr, status, error) {
                    //alert("Error " + xhr.responseText + " \n " + error);
                }
            })
        });
 [HttpPost]
        public ActionResult Testemail2()
        {
            string senderEmail = "testc@send.com";
            var mailMessage = new MailMessage();
            mailMessage.From = new MailAddress(senderEmail);
            mailMessage.To.Add("testTo@to.com");
            mailMessage.Subject = "Test EML Subject012";
            mailMessage.Body = "Test EML Body012";
            /// mark as DRAFT
            mailMessage.Headers.Add("X-Unsent", "1");
            //ATTACHMENTS
            var stream = new MemoryStream();
            EML_Stream(mailMessage, stream, senderEmail);
            stream.Position = 0;
            string variable = "";
            if(TempData["rootTest"] != null)
            {
                variable = TempData["rootTest"].ToString();
            }
            return Json(variable);
            //return File(stream, "message/rfc822", "Test_Email.eml");
        }
        private void EML_Stream(MailMessage msg, Stream str, string fromEmail)
        {
            string rootTemp = "";
            using(var client = new SmtpClient())
            {
                try
                {
                    string timeNow = DateTime.Now.ToString("MM-dd-yyyy-HHmmss");
                    var tempfolder = Path.Combine(Path.GetTempPath(), Assembly.GetExecutingAssembly().GetName().Name);
                    //tempfolder = Path.Combine("MailTest");
                    // Create temp folder to hold .eml file
                    tempfolder = Path.Combine(tempfolder, timeNow);
                    if (!Directory.Exists(tempfolder))
                    {
                        Directory.CreateDirectory(tempfolder);
                    }
                    rootTemp = tempfolder;
                    TempData["rootTest"] = rootTemp;
                client.UseDefaultCredentials = true;
                client.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory;
                client.PickupDirectoryLocation = tempfolder;
                client.Send(msg);


                }
                catch (System.Exception ex)
                {
                    TempData["Error"] = ex.Message.ToString();
                }

                // C:/temp/maildrop should contain .eml file.
                ///C:\temp\maildrop\
                //var filePath = Directory.GetFiles("C:\\temp\\maildrop\\").Single();
                string filePath = Directory.GetFiles(rootTemp).Single();
                /// Create new file and remove all lines with 'X-Sender:' or 'From:'
                string newFile = Path.Combine(rootTemp, "testemlemail.eml");
                using (var reader = new StreamReader(filePath))
                {
                    using (var writer = new StreamWriter(newFile))
                    {
                        string line;
                        while ((line = reader.ReadLine()) != null)
                        {
                            if (!line.StartsWith("X-Sender:") &&
                               !line.StartsWith("From:") &&
                                !line.StartsWith("X-Receiver: " + fromEmail) &&
                                !line.StartsWith("To: " + fromEmail))
                            {
                                writer.WriteLine(line);
                            }
                        }
                    }
                }
                using(var fs = new FileStream(newFile, FileMode.Open))
                {
                    fs.CopyTo(str);
                }
            }
        }
Bigbear
  • 489
  • 2
  • 5
  • 21