Posts Tagged Body

Email Excel Spreadsheet as Email Body Issues

Hello all. I had a production manager wanting an excel spreadsheet mailed as the body of the email. As some of you know the code generated by excel to produce the email is pretty crazy. But as a result, it showed up fine in Outlook and Android but it did not show the gridlines on the spreadsheet. So this code is based on the excellent work by Ron DeBruin over at http://www.rondebruin.nl/win/s1/outlook/bmail3.htm . I did a replacement for the HTML Range in this manner and the grid lines did appear. And the manager was happy.

Sub Mail_Selection_Range_Outlook_Body()
‘For Tips see: http://www.rondebruin.nl/win/winmail/Outlook/tips.htm
‘Don’t forget to copy the function RangetoHTML in the module.
‘Working in Excel 2000-2016
    Dim rng As Range
    Dim OutApp As Object
    Dim OutMail As Object
‘MsgBox Cells(5, 9).Value
    Set rng = Nothing
    On Error Resume Next
    ‘Only the visible cells in the selection
    Set rng = Selection.SpecialCells(xlCellTypeVisible)
    ‘You can also use a fixed range if you want
    ‘Set rng = Sheets(“YourSheet”).Range(“D4:D12”).SpecialCells(xlCellTypeVisible)
    On Error GoTo 0

    If rng Is Nothing Then
        MsgBox “The selection is not a range or the sheet is protected” & _
               vbNewLine & “please correct and try again.”, vbOKOnly
        Exit Sub
    End If

    With Application
        .EnableEvents = False
        .ScreenUpdating = False
    End With

    Set OutApp = CreateObject(“Outlook.Application”)
    Set OutMail = OutApp.CreateItem(0)

    On Error Resume Next
    With OutMail
        .BodyFormat = olFormatHTML
        .To = “you@you.com”       
           
               
       
         .CC = “”
        .BCC = “”
        .Subject = “Testing Purchase Order Email To Steve”
        .HTMLBody = RangetoHTML(rng)
        Replace .HTMLBody, “border-left:none”, “border-left:solid;border-width: 1px;border-color:black”
        Replace .HTMLBody, “border-right:none”, “border-right:solid;border-width: 1px;border-color:black”
        Replace .HTMLBody, “border-bottom:none”, “border-bottom:solid;border-width: 1px;border-color:black”
        Replace .HTMLBody, “border-top:none”, “border-bottom:solid;border-width: 1px;border-color:black”
        .Send
         ‘or use .Display
    End With
    On Error GoTo 0

    With Application
        .EnableEvents = True
        .ScreenUpdating = True
    End With

    Set OutMail = Nothing
    Set OutApp = Nothing
End Sub

, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,

Leave a comment

WCF and Email Attachments

First off I want to apologize for being away so long. It has been a crazy ride to say the least.

So a colleague of mine ran into an issue with WCF and emailing attachments and asked for help. In this block of code below it would always fail at:

Attachment attachment = new Attachment(fileAttachment.ContentStream, fileAttachment.Name);”     The error is : “Value cannot be null.
Parameter name: stream”

 

 

 
EmailSendInput emailSendInput = new EmailSendInput
                {
                    Attachments = new List<Attachment>(),
                    Body = model.Body,
                    To = new List<string> { model.EmailTo },
                    From = model.EmailFrom,
                    Subject = model.EmailSubject
                };

                if (model.Files != null)
                {
                    foreach (var currAttachment in model.Files)
                    {
                        if (currAttachment != null && currAttachment.ContentLength > 0)
                        {
                            // the filename needs to be nice looking
                            string fileName =
                                currAttachment.FileName.Substring(
                                    currAttachment.FileName.LastIndexOf(@”\”, System.StringComparison.Ordinal) + 1,
                                    currAttachment.FileName.Length
                                    – currAttachment.FileName.LastIndexOf(@”\”, System.StringComparison.Ordinal) – 1);

                            var attachment = new Attachment(currAttachment.InputStream, fileName);
                            emailSendInput.Attachments.Add(attachment);
                        }
                    }
                }

                B2BMortgageDataServiceAgent b2BMortgageDataServiceAgent = new B2BMortgageDataServiceAgent();
                EmailSendResponse emailSendResponse = b2BMortgageDataServiceAgent.SendEmail(emailSendInput);
                if (!emailSendResponse.Success)
                {
                    throw new Exception(emailSendResponse.Message);
                }
            }

public EmailSendResponse SendEmail(EmailSendInput input)
        {
            EmailSendResponse retVal = new EmailSendResponse();
            try
            {
               
                string smtpServer = “”
                string smtpPort = “”

                using (var client = new SmtpClient(smtpServer, Convert.ToInt32(smtpPort)))
                {
                    var mail = new MailMessage
                    {
                        From = new MailAddress(input.From),
                        Subject = input.Subject,
                        Body = input.Body
                    };
                    input.To.ForEach(t => mail.To.Add(t));

                    if (input.Attachments != null && input.Attachments.Count > 0)
                    {
                        foreach (var fileAttachment in input.Attachments)
                        {
                            //Code Crashes here
                            Attachment attachment = new Attachment(fileAttachment.ContentStream, fileAttachment.Name);
                            mail.Attachments.Add(attachment);
                        }
                    }

                    client.Send(mail);
                }

                retVal.Success = true;
            }
            catch (Exception exception)
            {
                retVal.Success = false;
                LogUtil.LogException(exception);

            
                retVal.Message = exception.ToString();
            }

            return retVal;
        }

and then the contract:

[DataContract]
    public class EmailSendInput
    {
        [DataMember]
        public string From { get; set; }

        [DataMember]
        public List<string> To { get; set; }

        [DataMember]
        public string Subject { get; set; }

        [DataMember]
        public string Body { get; set; }

        [DataMember]
        public List<Attachment> Attachments { get; set; }

    }

Implemented as:

public EmailSendResponse SendEmail(EmailSendInput input)
         {
             try
             {
                 return this.dataAgent.SendEmail(input);
             }
             catch (Exception e)
             {
                 this.logger.LogException(e, 2);
                 throw new FaultException(“An error occured in SendEmail. Error details : ” + this.BuildMessage(e));
             } 
         }

and the Email response:

[DataContract]
    public class EmailSendResponse
    {
        [DataMember]
        public bool Success { get; set; }

        [DataMember]
        public string Message { get; set; }
    }

So now we have the problem. I basically had to recreate his datamember for attachment in the contract EmailSendInput to a

public List<EmailEncodedAttachment> Attachments { get; set; }

and added a new contract called EmailEncodedAttachment and process how he was handling the attachment differently. I’ve also included the MVC controller calls in case it might help you as well.

 

SOLUTION:

[DataContract]
    public class EmailSendInput
    {
        [DataMember]
        public string From { get; set; }

        [DataMember]
        public List<string> To { get; set; }

        [DataMember]
        public string Subject { get; set; }

        [DataMember]
        public string Body { get; set; }

        [DataMember]
        public List<EmailEncodedAttachment> Attachments { get; set; }

    }

 

[DataContract]
    public class EmailEncodedAttachment
    {
        [DataMember]
        public string Base64Attachment;

        [DataMember]
        public string Name;

        /// <summary>
        /// One of the System.Net.Mime.MediaTypeNames
        /// </summary>
        [DataMember]
        public string MediaType;
    }
}
                retVal.Message = exception.ToString();
            }

            return retVal;
        }

 

public EmailSendResponse SendEmail(EmailSendInput input)
        {
            EmailSendResponse retVal = new EmailSendResponse();
            try
            {
               
                string smtpServer = ConfigurationManager.AppSettings[“SmtpServer”] ?? “url”;
                string smtpPort = ConfigurationManager.AppSettings[“SmtpPort”] ?? “portnum”;

                using (var client = new SmtpClient(smtpServer, Convert.ToInt32(smtpPort)))
                {
                    var mail = new MailMessage
                    {
                        From = new MailAddress(input.From),
                        Subject = input.Subject,
                        Body = input.Body
                    };
                    input.To.ForEach(t => mail.To.Add(t));

                    if (input.Attachments != null && input.Attachments.Count > 0)
                    {
                        foreach (var fileAttachment in input.Attachments)
                        {
                            mail.Attachments.Add(this.CreateAttachment(fileAttachment));
                        }
                    }

                    client.Send(mail);
                }

                retVal.Success = true;
            }
            catch (Exception exception)
            {
                retVal.Success = false;
                LogUtil.LogException(exception);
             
                retVal.Message = exception.ToString();
            }

            return retVal;
        }

 

The MVC controller action calls the service like so:

EmailSendInput emailSendInput = new EmailSendInput
                {
                    Attachments = new List<EmailEncodedAttachment>(),
                    Body = model.Body,
                    To = new List<string> { model.EmailTo },
                    From = model.EmailFrom,
                    Subject = model.EmailSubject
                };

                if (model.Files != null)
                {
                    foreach (var file in model.Files)
                    {
                        if (file != null && file.ContentLength > 0)
                        {
                            // the filename needs to be nice looking
                            string prettyFileName =
                                file.FileName.Substring(
                                    file.FileName.LastIndexOf(@”\”, System.StringComparison.Ordinal) + 1,
                                    file.FileName.Length
                                    – file.FileName.LastIndexOf(@”\”, System.StringComparison.Ordinal) – 1);

                            var attachment = this.CreateAttachment(prettyFileName, file.InputStream);
                            emailSendInput.Attachments.Add(attachment);
                        }
                    }
                }

                B2BMortgageDataServiceAgent b2BMortgageDataServiceAgent = new B2BMortgageDataServiceAgent();
                EmailSendResponse emailSendResponse = b2BMortgageDataServiceAgent.SendEmail(emailSendInput);
                if (!emailSendResponse.Success)
                {
                    throw new Exception(emailSendResponse.Message);
                }

 

and finally the encoding method which makes this possible:

private EmailEncodedAttachment CreateAttachment(string fileName, Stream stream)
        {
            EmailEncodedAttachment att = new EmailEncodedAttachment
            {
                Name = fileName,
                MediaType = System.Net.Mime.MediaTypeNames.Text.Plain
            };

            byte[] buffer = new byte[stream.Length];
            stream.Read(buffer, 0, (int)stream.Length);
            att.Base64Attachment = Convert.ToBase64String(buffer);

            return att;
        }

 

There you have it folks. I hope you have a great Sunday!

, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,

Leave a comment