2012-08-27 53 views
2

下面是我发送邮件代码...更改显示名称在C#

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

    nM.To.Add("[email protected]"); 
    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); 
} 

,这是我的web配置代码...

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

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

mM.From = new MailAddress("[email protected]","xyz"); 

,但在我案例我没有写发件人的邮件地址任何地方,我只是从网络配置,然后我将如何改变这个名字..我有当前登录用户在我的会话中,我想显示该名称作为发件人...

+0

的“从”,也就是在你的web.config据我可以告诉不被使用。该配置部分用于在您的SMTP服务器上配置身份验证,并且与实际消息无关。您可以简单地使用MailMessage.From属性来设置显示名称,就像您在上一段代码段中显示的那样。 – pleinolijf

回答

6

应该把它放在SMTP从标签

<smtp deliveryMethod="Network" from="XYZ&lt;[email protected]&gt;"> 
<network host="smtp.gmail.com" 
       defaultCredentials="false" userName="[email protected]" password="xyz" 
       port="587"/>