简体   繁体   中英

Formatting e-mail body HTML

How would I go about making the body work with HTML format. what do I need to add and what line would I need to add it? I have tried MailMessage.IsBodyHtml = true; but that did not work for me. Is this the way to do it? should that code be replacing another line or should it be on a line on its own?

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.Office.Interop;
using Microsoft.Office.Interop.Excel;
using System.Net;
using System.Net.Mail;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Button1_Click(object sender, EventArgs e)
        {
            const string subject = "ASSET RECOVERY";
            listBox1.Items.Clear();
            //1. Replace the password
            var fromAddress = new MailAddress("", ""); //Email address then Name
            const string fromPassword = ""; //Email Password
            string body = "";



            //2. Potentially replace any of the Host / Port combo if necessary
            var smtp = new SmtpClient
            {
                Host = "smtp.gmail.com",
                Port = 587,
                EnableSsl = true,
                DeliveryMethod = SmtpDeliveryMethod.Network,
                UseDefaultCredentials = false,
                Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
            };


            string path = "C:\\Users\\adrian.simonis\\Desktop\\VPN\\AdriansExcel3.xlsx ";
            //3. Replace the above with the actual path that your excel file is.

            Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
            Workbook wb = excel.Workbooks.Open(path);
            Worksheet excelSheet = wb.ActiveSheet;
            int rows = excelSheet.Rows.Count;
            int successfulSends = 0;


            for (int i = 1; i < rows; i++)
            {
                string mySendAddress = "";
                string myAsset = "";

                try
                {
                    body = <font size = "20" color = "red" style = "text-align:center;" > "ATTENTION\n\n" </ font >< br > +

"Company is collecting underutilized PCs and other surplus computing equipment. Retiring computers reduces a variety of annual costs, including corporate allocations, maintenance, licensing fees and labor associated with information protection and system patching.\n\n" +

"The following criteria is used to determine an underutilized device:\n\n" +



"Use Login Times and Keyboard / Mouse Activity, Load Average, CPU Utilization, Physical Memory Utilization, Software Usage, Disk Utilization\n\n" +



  "All of these factors are viewed over time scales: one week, four weeks and 16 weeks to determine if this asset falls under a low usage threshold\n\n" +

  "In order to support Aero IT Asset Reduction initiatives, this asset (ASSET TAG HERE) has been identified as underutilized and will be removed on.\n\n" +

"1 - 28 - 20\n\n" +

"If there is a critical business need to leave this device in place, please send an email justification to keep the asset to the following public folder\n\n" +





" | Sr.Desktop Technician\n\n" +

"CompanyAsset Recovery Support\n\n" +

"Email: \n\n" +

"Office: \n\n";

                    myAsset = excelSheet.Cells[i, 19].Value.ToString();
                    mySendAddress = excelSheet.Cells[i, 22].Value.ToString();
                    body = body.Replace("(ASSET TAG HERE)", myAsset); //his assetAssetTag1 ha
                    label2.Text = "Sending email to: " + mySendAddress + " with asset tag: " + myAsset;
                }
                catch
                {
                    System.Threading.Thread.Sleep(3000);
                    label2.Text = "Finished: reached empty excel cell with no send to address";
                    break;
                }

                //Send email here!
                var toAddress = new MailAddress(mySendAddress);
                using (var message = new MailMessage(fromAddress, toAddress)
                {
                    Subject = subject,
                    Body = body
                })

                {
                    try
                    {
                        smtp.Send(message);
                        listBox2.Items.Add(toAddress);
                    }
                    catch (ArgumentOutOfRangeException ex)
                    {
                        listBox1.Items.Add(toAddress);
                    }
                }

                successfulSends++;
                label1.Text = "Successful emails: " + successfulSends;
                System.Threading.Thread.Sleep(3000);

            }

            wb.Close();
        }
    }
}

So, after getting it to HTML its sending green.

"<html><font size = 20, color = red, style =text - align:center;>ATTENTION </ font >\n\n" +

"<html><font size = 10>Company is collecting underutilized PCs and other surplus computing equipment. Retiring computers reduces a variety of annual costs, including corporate allocations, maintenance, licensing fees and labor associated with information protection and system patching.</ font >\n\n" +

"The following criteria is used to determine an underutilized device:\n\n" +



"Use Login Times and Keyboard / Mouse Activity, Load Average, CPU Utilization, Physical Memory Utilization, Software Usage, Disk Utilization\n\n" +



  "All of these factors are viewed over time scales: one week, four weeks and 16 weeks to determine if this asset falls under a low usage threshold\n\n" +

  "In order to support Aero IT Asset Reduction initiatives, this asset (ASSET TAG HERE) has been identified as underutilized and will be removed on.\n\n" +

"1 - 28 - 20\n\n" +

"If there is a critical business need to leave this device in place, please send an email justification to keep the asset to the following public folder\n\n" +





"| Sr.Desktop Technician\n\n" +

"CompanyAsset Recovery Support\n\n" +

"Email:\n\n" +

"Office: phone\n\n</html>";

The HTML document you are creating isn't valid. Eg you are opening two tags, but never close them. Also as far as I can tell your inline-styles aren't valid (unless there is something I am missing here).

This line also looks like it should throw an error, when you are trying to run the program:

body = <font size = "20" color = "red" style = "text-align:center;" > "ATTENTION\n\n" </ font >< br > +

Instead of using string concatenation which is error prone and often leads to missing closing tags and other issues, an easy solution I sometimes use is to set up a valid HTML-template (eg in a resource file) that is populated by placeholders:

<!DOCTYPE html>
<html>
<head>
    <style>
        .attention {
            text-align: center;
            font-size: 20px;
            color: red;
        }
        .content {{
            color: black;
            font-size: 10px;
        }}
    </style>
</head>
<body>
<p class="attention">[PLACEHOLDER_TITLE]</p>

<p class="content">[PLACEHOLDER_CONTENT]</p>

<ol>
  <li>[PLACEHOLDER_LIST_ITEM_1]</li>
  <li>[PLACEHOLDER_LIST_ITEM_2]</li>
  <li>[PLACEHOLDER_LIST_ITEM_3]</li>
</ol>
</body>
</html>

These can then easily be replaced with the actual content later on and make the code much easier to read:

string body = (String)GetLocalResourceObject("EmailTemplate");
body.Replace("[PLACEHOLDER_TITLE]", title);
body.Replace("[PLACEHOLDER_CONTENT]", content);
...

Just to be clear: In your actual application you have to make sure that all characters are correctly escaped (in both the template and the replacement strings you are inserting into it).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM