Click here to Skip to main content
15,888,401 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net.Mail;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace ProjectBuzzUtils
{
    public static class EmailHelper
    {
        public static void SendEmail(string from, string toEmails, string ccEmails, string subject, object data, string templateType)
        {
            Dictionary<string, string> dataList = ExtractClassData(data);
            string body = CreateEmailBody(dataList, templateType);
            SendHtmlFormattedEmail(from, toEmails, ccEmails, subject, body);
        }
        private static string CreateEmailBody(Dictionary<string, string> replaceElement, string templateType)
        {
            string body = string.Empty;
            var templatePath = "~/Views/EmailTemplate/" + templateType + ".cshtml";
            using (StreamReader reader = new StreamReader(HttpContext.Current.Server.MapPath(templatePath)))
            {
                body = reader.ReadToEnd();
                foreach (var pair in replaceElement)
                {
                    body = body.Replace(pair.Key, pair.Value);
                }
            }
            return body;
        }

        private static void SendHtmlFormattedEmail(string from, string toEmails, string ccEmails, string subject, string body)
        {
            string fromEmail = ConfigurationManager.AppSettings["FromEmail"].ToString();
            string host = ConfigurationManager.AppSettings["Host"].ToString();
            SmtpClient smtpClient = new SmtpClient();
            int tryAgain = 10;
            bool failed = false;
            do
            {
                try
                {
                    failed = false;
                    using (MailMessage mailMessage = new MailMessage())
                    {
                        MailMessage mm = new MailMessage();
                        mm.Body = body;
                        mm.IsBodyHtml = true;
                        if (!string.IsNullOrEmpty(toEmails))
                        {
                            foreach (string email in toEmails.Split(','))
                            {
                                mm.To.Add(new MailAddress(email));
                            }
                        }
                        if (!string.IsNullOrEmpty(ccEmails))
                        {
                            foreach (string email in ccEmails.Split(','))
                            {
                                mm.CC.Add(new MailAddress(email));
                            }
                        }
                        mm.From = new MailAddress(from);
                        mm.Subject = subject;

                        smtpClient.Host = host;
                        smtpClient.Send(mm);
                    }
                }
                catch (Exception ex) // I would avoid catching all exceptions equally, but ymmv
                {

                    failed = true;
                    tryAgain--;
                    var exception = ex.Message.ToString();
                    smtpClient.Dispose();
                    //Other code for saving exception message to a log.
                }
            } while (failed && tryAgain != 0);
        }

        public static Dictionary<string, string> ExtractClassData(object o)
        {
            if (o == null)
                return new Dictionary<string, string>();

            var type = o.GetType();
            var propertyInfos = type.GetProperties()
                .Select(p => new
                {
                    Name = p.GetCustomAttribute<DisplayAttribute>() != null ? p.GetCustomAttribute<DisplayAttribute>().Name : p.Name,
                    FormatAttribute = p.GetCustomAttribute<DisplayFormatAttribute>(),
                    Property = p,
                    Type = p.PropertyType,
                    Value = p.GetValue(o),
                });

            var dictionary = new Dictionary<string, string>();
            foreach (var property in propertyInfos.Where(p => p.Value != null))
            {
                if (property.Value != null)
                {
                    dictionary.Add("$$$" + property.Name + "$$$", FormatValue(property.Value, property.Type, property.FormatAttribute));
                }
            }
            dictionary.Add("$$$Date_String$$$", DateTime.UtcNow.AddHours(5.5).ToString());
            return dictionary;
        }
        private static string FormatValue(object value, Type type, DisplayFormatAttribute format)
        {
            if (value == null)
                return null;
            if (type.IsEnum || (Nullable.GetUnderlyingType(type) != null && Nullable.GetUnderlyingType(type).IsEnum))
            {
                if (!Enum.IsDefined(type, value))
                    return value.ToString();

                var display = type.GetField(value.ToString()).GetCustomAttribute<DisplayAttribute>();
                if (display != null)
                    return display.Name;
                return value.ToString();
            }
            if (type == typeof(string))
                return (string)value;

            if (format != null)
                return string.Format(format.DataFormatString, value);
            return value.ToString();
        }
    }
}


What I have tried:

/* -------------------------------------
GLOBAL RESETS
------------------------------------- */
img {
border: none;
-ms-interpolation-mode: bicubic;
max-width: 100%;
}

body {
background-color: #f6f6f6;
font-family: sans-serif;
-webkit-font-smoothing: antialiased;
font-size: 14px;
line-height: 1.4;
margin: 0;
padding: 0;
-ms-text-size-adjust: 100%;
-webkit-text-size-adjust: 100%;
}

table {
border-collapse: separate;
mso-table-lspace: 2pt;
mso-table-rspace: 2pt;
width: 100%;
}

table td {
font-family: sans-serif;
font-size: 14px;
vertical-align: top;
}

table {
border: medium;
border-color: burlywood;
}

td tr {
border: medium;
border-color: Highlight;
}
/* -------------------------------------
BODY & CONTAINER
------------------------------------- */
.body {
background-color: #f6f6f6;
width: 100%;
}
/* Set a max-width, and make it display as block so it will automatically stretch to that width, but will also shrink down on a phone or something */
.container {
display: block;
Margin: 0 auto !important;
/* makes it centered */
max-width: 580px;
padding: 10px;
width: 580px;
}
/* This should also be a block element, so that it will fill 100% of the .container */
.content {
box-sizing: border-box;
display: block;
Margin: 0 auto;
max-width: 900px;
padding: 6px;
}
/* -------------------------------------
HEADER, FOOTER, MAIN
------------------------------------- */
.main {
background: #ffffff;
border-radius: 3px;
width: 100%;
}

.wrapper {
box-sizing: border-box;
padding: 20px;
}

.content-block {
padding-bottom: 10px;
padding-top: 10px;
}

.footer {
clear: both;
Margin-top: 10px;
text-align: center;
width: 100%;
}

.footer td,
.footer p,
.footer span,
.footer a {
color: #999999;
font-size: 12px;
text-align: center;
}
/* -------------------------------------
TYPOGRAPHY
------------------------------------- */
h1,
h2,
h3,
h4 {
color: #000000;
font-family: sans-serif;
font-weight: 400;
line-height: 1.4;
margin: 0;
Margin-bottom: 20px;
}

h1 {
font-size: 35px;
font-weight: 300;
text-align: center;
text-transform: capitalize;
}

p,
ul,
ol {
font-family: sans-serif;
font-size: 14px;
font-weight: normal;
margin: 0;
Margin-bottom: 15px;
}

p li,
ul li,
ol li {
list-style-position: inside;
margin-left: 5px;
}

a {
color: #3498db;
text-decoration: underline;
}


/* -------------------------------------
OTHER STYLES THAT MIGHT BE USEFUL
------------------------------------- */
.last {
margin-bottom: 0;
}

.first {
margin-top: 0;
}

.align-center {
text-align: center;
}

.align-right {
text-align: right;
}

.align-left {
text-align: left;
}

.clear {
clear: both;
}

.mt0 {
margin-top: 0;
}

.mb0 {
margin-bottom: 0;
}

.preheader {
color: transparent;
display: none;
height: 0;
max-height: 0;
max-width: 0;
opacity: 0;
overflow: hidden;
mso-hide: all;
visibility: hidden;
width: 0;
}

.powered-by a {
text-decoration: none;
}

hr {
border: 0;
border-bottom: 1px solid #f6f6f6;
Margin: 20px 0;
}





 



Thank you for the feedback !

Project Buzz User Feedback
$$$Date$$$






Hi, $$$Employee_Name$$$
Thank you for the feedback !






Employee Id : $$$Employee_Id$$$
Employee Name : $$$Employee_Name$$$
Employee Code : $$$Employee_Code$$$
Query Type : $$$QueryType$$$
Message : $$$Message$$$









Regards,


Project Buzz Work Flow and Production














Powered by OPTUM SOURCE.




This e-mail, including attachments, may include confidential and/or proprietary information, and may be used only by the person or entity to which it is addressed. If the reader of this e-mail is not the intended recipient or his or her authorized agent, the reader is hereby notified that any dissemination, distribution or copying of this e-mail is prohibited. If you have received this e-mail in error, please notify the sender by replying to this message and delete this e-mail immediately.








 
Posted
Updated 31-Oct-18 11:49am
Comments
Yvan Rodrigues 31-Oct-18 17:20pm    
What is the problem you are encountering?
Richard Deeming 2-Nov-18 12:06pm    
A code-dump is not a question.

1 solution

I would highly recommend that you run this in debug mode and go step-by-step through this, find out where there is a problem (if any), and then come back here and trim out all the code that we don't need to see.
If it should turn out to be the SMTP sending block, bring the exception messages back.

Other things that would help are going to be the AppSettings being referenced; if you are using gmail as an example, the gmail account associated with the from address will need to be set to allow less secure applications

Most mail hosts also will require account credentials before sending; the way you have this setup uses neither default credentials nor a username/password combination.

The way that the try...catch is setup is not doing you any favors- if any one of the email addresses are bad, it is going to keep trying to send to everyone all over again.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900