从Powershell发送样式化HTML电子邮件(在Powershell中使用.NET DLL)

介绍 (Introduction)

I have written a small mail sending function in .NET that I leverage in all my systems I develop. I had to develop a bunch of Powershell scripts to monitor and report on various process and instead of going throught the effort of reworking my .NET DLL and a Powershell function I opted to call the .NET DLL directly from Powershell.

我已经在.NET中编写了一个小型邮件发送功能,可以在我开发的所有系统中利用。 我不得不开发一堆Powershell脚本来监视和报告各种过程,而不是费力地重做.NET DLL和Powershell函数,我选择直接从Powershell调用.NET DLL。

My email DLL gives the ability to mail styled email messages. You can get the DLL from http://blog.ittelligence.com/wp-content/uploads/2019/05/ITtelligence.Email_.dll_.zip

我的电子邮件DLL可以发送样式化电子邮件消息。 您可以从http://blog.ittelligence.com/wp-content/uploads/2019/05/ITtelligence.Email_.dll_.zip获取DLL

This method also produces the same result in Microsoft Outlook and other mail clients. See GMail preview of mail below.

此方法在Microsoft Outlook和其他邮件客户端中也产生相同的结果。 请参阅下面的GMail邮件预览。

Below you can see how to use this DLL to do the same from Powershell

在下面您可以看到如何使用此DLL从Powershell中执行相同的操作

电源外壳 (Powershell)

The first step is to make the DLL methods available in Powershell

第一步是使DLL方法在Powershell中可用

[Reflection.Assembly]::LoadFile("C:\SOMEPATH\ITtelligence.Email\bin\Debug\ITtelligence.Email.dll") 

One of the parameters that my DLL accepts is a list collection of string. To be able to pass this to the .NET DLL, first we create a string array

我的DLL接受的参数之一是字符串的列表集合。 为了能够将此传递给.NET DLL,首先我们创建一个字符串数组

[string[]]$toEmailAddressesArray = "shaun.vermaak@ittelligence.com","someoneelse@ittelligence.com"; 

Once we have the string array we can cast it as a list collection type string

一旦有了字符串数组,就可以将其转换为列表集合类型的字符串

[Collections.Generic.List[String]]$toEmailAddressesList = $toEmailAddressesArray; 

To make it easier to manage errors, the Send method returns a main result of type boolean based on the overall result and 

为了更容易管理错误,Send方法根据总体结果返回一个布尔类型的主结果,并且

detailed error as a reference variable.

详细错误作为参考变量。

$ReturnMessage = ""; 

This is the .NET Send method definition

这是.NET Send方法定义

public static bool Send(List<string> MailAddresses, string Host, int Port, bool SSL, int Timeout, string Domain, string UserName, string Password, string From, string Subject, string Title, string Body, string LogoImage, string BackgroundImage, out string Ret 

Based on the definition above, here's an example of calling the Send method. The LogoImage and BackgroundImage can be physical locations to images or a base64 string using a service like https://www.base64-image.de/

根据上面的定义,这是调用Send方法的示例。 使用诸如https://www.base64-image.de/的服务, LogoImageBackgroundImage可以是图像或base64字符串的物理位置。

[ITtelligence.EMail]::Send($mailAddresses, "in-v3.mailjet.com", 587, $true, 60000, "", "REMOVED", "REMOVED", "shaun.vermaak@ittelligence.com", "Sample Subject", "Sample Title", "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.", "c:\temp\ACME.png", "c:\Temp\Tile002.jpg",[ref] $ReturnMessage) 

For reference, here's the full script

供参考,这是完整的脚本

[Reflection.Assembly]::LoadFile("C:\SOMEPATH\ITtelligence.Email\bin\Debug\ITtelligence.Email.dll")

[string[]]$toEmailAddressesArray = "shaun.vermaak@ittelligence.com","someoneelse@ittelligence.com";

[Collections.Generic.List[String]]$toEmailAddressesList = $toEmailAddressesArray;

$ReturnMessage = "";

[ITtelligence.EMail]::Send($mailAddresses, "in-v3.mailjet.com", 587, $true, 60000, "", "REMOVED", "REMOVED", "someone@ittelligence.com", "Sample Subject", "Sample Title", "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.", "c:\temp\ACME.png", "c:\Temp\Tile002.jpg",[ref] $ReturnMessage) 


(
)

.NET DLL源代码 (.NET DLL Source Code)

If you are interested in the DLL source code, you can find it below or via this repo

如果您对DLL源代码感兴趣,可以在下面或通过此仓库找到它

https://github.com/svermaak/ITtelligence.Emailhttps://github.com/svermaak/ITtelligence.Email

https://github.com/svermaak/ITtelligence.Emailhttps://github.com/svermaak/ITtelligence.Email

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Mail;
using System.Net.Mime;
using System.Text;
using System.Threading.Tasks;
using static System.Net.Mime.MediaTypeNames;

namespace ITtelligence
{
    public class EMail
    {
        public static bool Send(List<string> MailAddresses, string Host, int Port, bool SSL, int Timeout, string Domain, string UserName, string Password, string From, string Subject, string Title, string Body, string LogoImage, string BackgroundImage, out string ReturnMessage)
        {
            try
            {
                SmtpClient client = new SmtpClient();
                client.DeliveryMethod = SmtpDeliveryMethod.Network;
                client.Host = Host;
                client.Port = Port;
                client.EnableSsl = SSL;
                client.Timeout = Timeout;


                if ((!string.IsNullOrEmpty(Domain)) && (!string.IsNullOrEmpty(UserName)) && (!string.IsNullOrEmpty(Password)))
                {
                    client.UseDefaultCredentials = false;
                    client.Credentials = new System.Net.NetworkCredential(UserName, Password, Domain);
                }
                else if ((!string.IsNullOrEmpty(UserName)) && (!string.IsNullOrEmpty(Password)))
                {
                    client.UseDefaultCredentials = false;
                    client.Credentials = new System.Net.NetworkCredential(UserName, Password);
                }
                else
                {
                    client.UseDefaultCredentials = false;
                }

                MailMessage mail = new MailMessage();

                mail.From = new MailAddress(From);
                foreach (string mailAddress in MailAddresses.Distinct().ToArray())
                {
                    if (!string.IsNullOrEmpty(mailAddress))
                    {
                        mail.To.Add(new MailAddress(mailAddress)); ;
                    }
                }

                // If file doesn't exist, perhaps it is base64 image?
                if (!File.Exists(LogoImage))
                {
                    LogoImage = LoadBase64ImageIntoTEMP(LogoImage);
                }
                if (!File.Exists(BackgroundImage))
                {
                    BackgroundImage = LoadBase64ImageIntoTEMP(BackgroundImage);
                }

                // Alternate View HTML version
                LinkedResource logoLinkedResource = new LinkedResource(LogoImage);
                LinkedResource backgroundLinkedResource = new LinkedResource(BackgroundImage);
                logoLinkedResource.ContentId = Guid.NewGuid().ToString();
                backgroundLinkedResource.ContentId = Guid.NewGuid().ToString();
                string avHtmlBody = $"<html><head></head><body style='background-image: url(\"cid:{backgroundLinkedResource.ContentId}\");background-repeat: repeat;'><center><img src=\"cid:{logoLinkedResource.ContentId}\"></center><h1>{Title}</h1>{Body}</body></html>";
                AlternateView avHtml = AlternateView.CreateAlternateViewFromString(avHtmlBody, null, MediaTypeNames.Text.Html);
                avHtml.LinkedResources.Add(logoLinkedResource);
                avHtml.LinkedResources.Add(backgroundLinkedResource);
                mail.AlternateViews.Add(avHtml);

                // HTML version
                Attachment backgroundAttachment = new Attachment(BackgroundImage);
                Attachment logoAttachment = new Attachment(LogoImage);
                string htmlBody = $"<html><head></head><body style='background-image: url(\"{backgroundAttachment.Name}\");background-repeat: repeat;'><center><img src=\"cid:{logoAttachment.Name}\"></center><h1>{Title}</h1>{Body}</body></html>";
                mail.Body = htmlBody;
                mail.IsBodyHtml = true;
                mail.Attachments.Add(logoAttachment);
                mail.Attachments.Add(backgroundAttachment);

                mail.Subject = Subject;
                client.Send(mail);
                ReturnMessage = "Send";

                return true;
            }
            catch (Exception ex)
            {
                ReturnMessage = ex.Message;
                Console.WriteLine(ex.Message);
                return false;
            }
        }
        private static string LoadBase64ImageIntoTEMP(string Base64String)
        {
            try
            {
                byte[] bytes = Convert.FromBase64String(Base64String);

                System.Drawing.Image image;
                using (MemoryStream ms = new MemoryStream(bytes))
                {
                    string temporaryFileName = "";

                    temporaryFileName = Path.Combine(Path.GetTempPath(), System.Guid.NewGuid().ToString() + ".jpg");
                    image = System.Drawing.Image.FromStream(ms);
                    image.Save(temporaryFileName, System.Drawing.Imaging.ImageFormat.Jpeg);

                    return temporaryFileName;
                }
            }
            catch
            {
               
            }
            return null;
        }
    }
} 

结论 (Conclusion)

I hope you found this tutorial useful. You are encouraged to ask questions, report any bugs or make any other comments about it below. 

希望本教程对您有所帮助。 鼓励您在下面提出问题,报告任何错误或对此作出任何其他评论。

Note: If you need further "Support" about this topic, please consider using the Ask a Question feature of Experts Exchange. I monitor questions asked and would be pleased to provide any additional support required in questions asked in this manner, along with other EE experts...  

注意 :如果您需要有关此主题的更多“支持”,请考虑使用Experts Exchange 的“提问”功能。 我会监督提出的问题,并很高兴与其他电子工程师一起提供以这种方式提出的问题所需的任何其他支持...

Please do not forget to press the "Thumbs Up" button if you think this article was helpful and valuable for EE members.

如果您认为本文对EE成员有用且有价值,请不要忘记按下“竖起大拇指”按钮。

It also provides me with positive feedback. Thank you!

它还为我提供了积极的反馈。 谢谢!

翻译自: https://www.experts-exchange.com/articles/33549/Sending-styled-HTML-email-from-Powershell-Using-a-NET-DLL-in-Powershell.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值