当发件人邮件来自C#中的Web配置时,更改邮件中发件人的显示名称

时间:2012-08-27 08:01:26

标签: asp.net c#-4.0 smtp

以下是我发送邮件的代码......

 public void SendBy(string to, string subject, string body)
{
    MailMessage nM = new System.Net.Mail.MailMessage();

    nM.To.Add("abc@compulynx.org");
    nM.Subject = subject;
    nM.Attachments.Add(new Attachment(oStream, Fname));
    nM.Body = body;
    System.Configuration.Configuration config = WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath);
    System.Net.Configuration.MailSettingsSectionGroup settings = (System.Net.Configuration.MailSettingsSectionGroup)config.GetSectionGroup("system.net/mailSettings");

    SmtpClient client = new SmtpClient(settings.Smtp.Network.Host);
    client.Credentials = new NetworkCredential(settings.Smtp.Network.UserName, settings.Smtp.Network.Password);

    client.EnableSsl = true;
    client.Send(nM);
}

这是我的网络配置代码......

<system.net>
     <mailSettings>
        <smtp deliveryMethod="Network" from="xyz@gmail.com" >
            <network host="smtp.gmail.com" 
                    defaultCredentials="false" userName="xyz@gmail.com" password="xyz"
                    port="587"/>
        </smtp>
    </mailSettings>
</system.net>

此代码工作正常,但我将如何更改发件人显示名称,通常我们会像这样使用

 mM.From = new MailAddress("xyz@gmail.com","xyz");

但在我的情况下,我不是在任何地方编写发件人邮件地址,我只是从web配置,然后我将如何更改该名称..我在我的会话中有当前登录用户,我想将该名称显示为发件人......

2 个答案:

答案 0 :(得分:6)

应该把它放在标签

的smtp上
<smtp deliveryMethod="Network" from="XYZ&lt;xyz@gmail.com&gt;">
<network host="smtp.gmail.com" 
                defaultCredentials="false" userName="xyz@gmail.com" password="xyz"
                port="587"/>

答案 1 :(得分:0)

您可以在web.config中设置如下:

<network host="smtp.gmail.com" 
         defaultCredentials="false" 
         userName="&quot;xyz&quot;&lt;xyz@gmail.com&gt;"
         password="xyz" 
         port="587"/>

参考supported formats for MailAddress