简体   繁体   中英

system.net.mail editing mail content

I am using system.net.mail library for sending a user information about some made actions. At program runtime I am collecting some information and later on I would like to show it to user. The mail content would look like this:

Hello user,
this is your id in system.
*if he chosen option1*
You chosen option 1 value
*if he chosen option2*
You chosen option 2 value
*if he chosen option3*
You chosen option 3 value

The problem is that I didn't find a way how I could change mail content (which is written in html, and added to resources) at program runtime.

Anyone can suggest how I should editing mail content depending of chosen values or maybe there is any alternatives?

Example of mail:

`<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">`
<html>
 <head>
  <META http-equiv=Content-Type content="text/html">
 </head>
 <body>
  <p>Hello user,</p>
  <p>This is your id in system : {0}</p>
/*
And the dificult part here: 
    if he chosen option1 in program I want in email to show that option 1 value.
    And if he didn't chosen it I don't wanna show it to him. 
*/        
 </body>
</html>

You could store html in an XML file and populate the content via string.Format like so: -

<?xml version="1.0" encoding="utf-8" ?>
<Email>
    <FromAddress>from</FromAddress>
    <ToAddress>to</ToAddress>
    <Subject>subject line</Subject>
    <EmailBody>
        <![CDATA[
     <html>
<head>
    <title>Customer</title>
</head>
        <div valign="top">
             <font color="#666666" face="Arial, Helvetica, sans-serif, Verdana" size="2">
             <p>Hello user.</p>
             <p><strong>This is your ID in the system: </strong>{0}<br />
             <strong>You chose option: </strong>{1}<br /></p>
             </font>
        </div>
</html> 
      ]]>
    </EmailBody>
</Email>

Code (populate and send): -

int custId = //provide customer id
string option = //customers selected option
string custEmail = //customers email

MailMessage mail = GetHtmlEmail();

string message = string.Format(mail.Body, custId, option);

mail.IsBodyHtml = true;
mail.Body = message;

using (SmtpClient smtp = new SmtpClient())
{
    smtp.Send(mail);
}

Reading in the email markup + setting some properties of the mail object: -

private MailMessage GetHtmlEmail()
{
    MailMessage mail = new MailMessage();
    XmlTextReader xReader = new XmlTextReader(Server.MapPath("PATH TO EMAIL.XML"));

    while (xReader.Read())
    {
        switch (xReader.Name)
        {
            case "ToAddress":
                mail.To.Add(xReader.ReadElementContentAs(typeof(string), null).ToString());
                break;
            case "FromAddress":
                mail.From = new MailAddress(xReader.ReadElementContentAs(typeof(string), null).ToString());
                break;
            case "Subject":
                mail.Subject = xReader.ReadElementContentAs(typeof(string), null).ToString();
                break;
            case "EmailBody":
                mail.Body = xReader.ReadElementContentAs(typeof(string), null).ToString();
                break;
            default:
                break;
        }
    }

    return mail;
}

Edit* If you don't want this <strong>You chose option: </strong>{1}<br /> to appear AT ALL if the customer chose no option, then you could do this (though a bit hacky): -

if(!string.IsNullOrEmpty(option))
{
    option = string.Format("<strong>You chose option: </strong>{1}<br />", option);
}
else
{
    option = string.Empty;
}

Then pass it in as normal: -

string message = string.Format(mail.Body, custId, option);

Making sure to replace this line in the markup <strong>You chose option: </strong>{1}<br /> with {1}

I have a real world situation, that I need to do this with email, and I used templates. You could try to create a template to your email body, with variables, and create this body occording to your situation, changing the variables to their correct value. Example of a template:

<p>Hello user [User]</p>
<p>This is your id in system : [ID]</p>
<p>[ChoosenOption]</p>

Create a resource file, so you can get this template by its name. You gonna have to create a method that will change those variables, like this example:

public String ProcessTemplate(String templateName, dynamic variables)
{
    String template = MethodThatSearchOnResourceAndReturnsTemplateByItsName(templateName);
        if (String.IsNullOrWhiteSpace(template))
        {
            return String.Empty;
        }

        if (variables == null)
        {
            return template;
        }

        PropertyInfo[] properties = ((Object)variables).GetType().GetProperties();
        foreach (PropertyInfo prop in properties )
        {
            template = template.Replace("[" + prop.Name + "]", propriedade.GetValue(properties, null));
        }

        return template;
 }

Now you draw your template like this:

String body = ProcessTemplate("TemplateName", new
{
   User = the user name,
   ID = this user id,
   ChoosenOption = ReturnChoosenOptionHtml()
});

private String ReturnChoosenOptionHtml()
{
    String html = String.Empty;
    if(chooseOption1)
        html += "xptoHTML";
    if(choosenOption2)
        html += "abcdHTML";
    return html;
}

The final result will be an email with those [Variables] changed with the values you passed.

当您从用户提交表单时,将其信息保存在会话中,然后在发送邮件后显示一个弹出窗口,并将您的信息与会话连接。

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