如何以编程方式发送Outlook消息模板? [英] How can I send outlook message template programatically?

查看:162
本文介绍了如何以编程方式发送Outlook消息模板?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在向用户使用.html tosend电子邮件模板。但它带来的问题是我的代码无法成功,如果模板被特别更改,如果有更多的图像添加到模板,所以我需要每次更改代码。



任何人都可以建议我发送电子邮件作为常用方法的最佳方式,而不关心有多少图像模板包含,我需要一个常用的方法来完成这项工作。只传递任何类型的模板。



我尝试过:



  public   class  E_Mail 
{

public void sendEmail( string 收件人,字符串发​​件人,字符串 StrContent)
{

MailMessage message = new MailMessage();
MailAddress Sender = new MailAddress(sender);
MailAddress receiver = new MailAddress(To);

LinkedResource aa = new LinkedResource(logo = System.AppDomain.CurrentDomain.BaseDirectory + @ Images / a.png);
LinkedResource bb = new LinkedResource(logo = System.AppDomain.CurrentDomain.BaseDirectory + @ Images / b.png);

logo.ContentId = a;
blueImg.ContentId = b;

AlternateView av1 = AlternateView.CreateAlternateViewFromString( + StrContent, null ,MediaTypeNames.Text.Html);

av1.LinkedResources.Add(aa);
av1.LinkedResources.Add(bb);

message.AlternateViews.Add(av1);

message.Subject = 这是主题;

message.From = Sender;

message.To.Add(To);

message.IsBodyHtml = true ;

尝试
{
SmtpClient client = new SmtpClient(ConfigurationManager.AppSettings [ smtpServer]。ToString());
client.UseDefaultCredentials = true ;
client.Send(message);
}

catch (例外情况)
{
throw new System.ArgumentException( 尝试发送电子邮件,ex)时出错;
}


}
}

解决方案

您将需要一些方法来识别链接的资源。



如果您的模板的结构使得资源将永远是存储在 images / {ContentID} .png 中,然后您可以使用正则表达式 [ ^ ]提取它们:

  public   static   class 电子邮件
{
private 静态 readonly 正则表达式ContentIDPattern = 正则表达式( @ cid :(?< id> [A-Za-z0-9 \ -_] +),RegexOptions.ExplicitCapture);

private static ISet< string> ExtractContentIDs( string content)
{
var result = new HashSet< string>(StringComparer.OrdinalIgnoreCase);
foreach (匹配匹配 ContentIDPattern.Matches(content))
{
string id = match.Groups [ id ]值。
result.Add(id);
}

返回结果;
}

private static AlternateView CreateHtmlView( string content)
{
AlternateView result = AlternateView.CreateAlternateViewFromString(content, null ,MediaTypeNames.Text html的);

string basePath = System.AppDomain.CurrentDomain.BaseDirectory;
basePath = Path.Combine(basePath, Images);

foreach string id in ExtractContentIDs(content))
{
string path = Path.Combine(basePath,id + 。png);
result.LinkedResources.Add( new LinkedResource(path)
{
ContentId = id,
});
}

返回结果;
}

public static void SendEmail( string to, string sender, string content)
{
使用 var message = new MailMessage())
{
message.From = new MailAddress(发送者);
message.To.Add( new MailAddress(to));
message.Subject = 这是主题;

AlternateView body = CreateHtmlView(content);
message.AlternateViews.Add(body);

尝试
{
// TODO:切换到使用正确的配置元素:
var client = new SmtpClient(ConfigurationManager.AppSettings [ smtpServer]);
client.UseDefaultCredentials = true ;
client.Send(message);
}
catch (例外情况)
{
throw new InvalidOperationException( 尝试时出错发送电子邮件,ex);
}
}
}
}



如果您的资源不符合该约定,那么您将去必须将内容ID及其相应路径列表传递到 SendEmail 函数。



注意:您应该使用 appSettings 来配置您的SMTP设置。 us / library / ms164240(v = vs.110).aspx>专用 system.net/mailSettings/smtp 元素 [ ^ ]。这将使您更好地控制配置,并且您只需使用新的SmtpClient()(没有参数)来获取配置的设置。


I am using .html tosend email templates to users. but it comes with problem my code does not work successful if template is changed specially if there are more images added to template so i need to change the code every time.

can anybody suggest me the best way to send the email as common method without caring how many images template contains, i need a common method to do this job. only passing the template of any kind.

What I have tried:

public class E_Mail
   {

       public void sendEmail(string To,string sender ,string StrContent)
       {

           MailMessage message = new MailMessage();
           MailAddress Sender = new MailAddress(sender );
           MailAddress receiver = new MailAddress(To);

           LinkedResource aa = new LinkedResource(logo =System.AppDomain.CurrentDomain.BaseDirectory + @"Images/a.png");
           LinkedResource bb= new LinkedResource(logo =System.AppDomain.CurrentDomain.BaseDirectory + @"Images/b.png");

           logo.ContentId = "a";
           blueImg.ContentId = "b";

           AlternateView av1 = AlternateView.CreateAlternateViewFromString("" + StrContent, null, MediaTypeNames.Text.Html);

           av1.LinkedResources.Add(aa);
           av1.LinkedResources.Add(bb);

           message.AlternateViews.Add(av1);

           message.Subject = "This is subject";

           message.From = Sender;

           message.To.Add(To);

           message.IsBodyHtml = true;

           try
           {
               SmtpClient client = new SmtpClient(ConfigurationManager.AppSettings["smtpServer"].ToString());
               client.UseDefaultCredentials = true;
               client.Send(message);
           }

           catch (Exception ex)
           {
               throw new System.ArgumentException("There was an error when trying to send the email", ex);
           }


       }
   }

解决方案

You're going to need some way to identify the linked resources.

If your templates are structured such that the resources will always be stored in images/{ContentID}.png, then you might be able to use a regular expression[^] to extract them:

public static class Email
{
    private static readonly Regex ContentIDPattern = new Regex(@"cid:(?<id>[A-Za-z0-9\-_]+)", RegexOptions.ExplicitCapture);
    
    private static ISet<string> ExtractContentIDs(string content)
    {
        var result = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
        foreach (Match match in ContentIDPattern.Matches(content))
        {
            string id = match.Groups["id"].Value;
            result.Add(id);
        }
        
        return result;
    }
    
    private static AlternateView CreateHtmlView(string content)
    {
        AlternateView result = AlternateView.CreateAlternateViewFromString(content, null, MediaTypeNames.Text.Html);
        
        string basePath = System.AppDomain.CurrentDomain.BaseDirectory;
        basePath = Path.Combine(basePath, "Images");
        
        foreach (string id in ExtractContentIDs(content))
        {
            string path = Path.Combine(basePath, id + ".png");
            result.LinkedResources.Add(new LinkedResource(path)
            {
                ContentId = id,
            });
        }
        
        return result;
    }
    
    public static void SendEmail(string to, string sender, string content)
    {
        using (var message = new MailMessage())
        {
            message.From = new MailAddress(sender);
            message.To.Add(new MailAddress(to));
            message.Subject = "This is subject";
            
            AlternateView body = CreateHtmlView(content);
            message.AlternateViews.Add(body);
            
            try
            {
                // TODO: Switch to using the proper configuration element:
                var client = new SmtpClient(ConfigurationManager.AppSettings["smtpServer"]);
                client.UseDefaultCredentials = true;
                client.Send(message);
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException("There was an error when trying to send the email", ex); 
            }
        }
    }
}


If your resources don't follow that convention, then you're going to have to pass the list of content IDs and their corresponding paths into the SendEmail function.

NB: Rather than using the appSettings to configure your SMTP settings, you should use the dedicated system.net/mailSettings/smtp element[^]. This will give you much greater control over the configuration, and you'll just need to use new SmtpClient(), with no parameters, to pick up the configured settings.


这篇关于如何以编程方式发送Outlook消息模板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆