Форматирование тела письма HTML - PullRequest
0 голосов
/ 23 января 2020

Как бы я go заставил тело работать в формате HTML. что мне нужно добавить и какую строку мне нужно добавить? Я пробовал MailMessage.IsBody Html = true; но это не сработало для меня. Это способ сделать это? должен ли этот код заменять другую строку или он должен находиться на отдельной строке?

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();
        }
    }
}

Итак, после получения значения HTML отправка зеленого цвета.

"<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>";

1 Ответ

0 голосов
/ 23 января 2020

Документ HTML, который вы создаете, недействителен. Например, вы открываете два тега, но никогда не закрываете их. Кроме того, насколько я могу судить, ваши inline-стили недопустимы (если только здесь нет чего-то, что мне не хватает).

Эта строка также выглядит так, как будто она выдает ошибку, когда вы пытаетесь запустить программа:

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

Вместо использования конкатенации строк, которая подвержена ошибкам и часто приводит к отсутствию закрывающих тегов и другим проблемам, простое решение, которое я иногда использую, - установить действительный шаблон HTML (например, в файле ресурсов), который заполняется местозаполнителями:

<!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>

Позже они могут быть легко заменены фактическим содержимым и значительно упростят чтение кода:

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

Просто чтобы прояснить: в вашем реальном приложении вы должны убедиться, что все символы правильно экранированы (как в шаблоне, так и в замещающих строках, которые вы вставляете в него).

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...