我从我的网站(.NET Framework 2.0,IIS 7)发送邮件
MailAddress from = new MailAddress("from@email.com", "Name Name");
MailAddress to = new MailAddress("to@email.com", "");
MailMessage mm = new MailMessage(from, to);
mm.Subject = subject;
mm.Body = body;
using ( mm )
{
if (attach != null)
mm.Attachments.Add(attach);
mm.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient(mailServer);
if (!string.IsNullOrEmpty(mailPort))
smtp.Port = int.Parse(mailPort);
smtp.Credentials = new System.Net.NetworkCredential(username, pass);
smtp.Send(mm);
}
但是收到信件时没有显示名称(“姓名”),只有电子邮件。
您是否知道可能导致此问题的原因?
我确定,电子邮件客户端不会忽略显示名称!客户端是Outlook。
当应用程序将对象mm
传输到服务器时,属性From
为{"Name Name" <from@email.com>}
。为什么服务器删除名称?
答案 0 :(得分:2)
我也遇到过这个问题,但发现MailAddress也采用了第三个编码参数。所以不要使用:
MailAddress from = new MailAddress("from@email.com", "Name Name");
尝试其中一些人:
MailAddress from = new MailAddress("from@email.com", "Name Name", Encoding.ASCII);
MailAddress from = new MailAddress("from@email.com", "Name Name", Encoding.UTF8);
MailAddress from = new MailAddress("from@email.com", "Name Name", Encoding.Unicode);
此列表不受限制,您可以使用其他编码选项。我使用gmail并在启用Less Secure Apps的访问权限后,在使用SmtpClient后它适用于所有这些。
答案 1 :(得分:0)
/// <summary>
/// SMTP服务发送邮件
/// </summary>
/// <param name="mailSubjct">邮件主题</param>
/// <param name="mailBody">邮件内容(html)</param>
/// <param name="mailFrom">发件地址</param>
/// <param name="mailAddress">收件地址</param>
/// <param name="hostIp">SMTP主机IP</param>
/// <param name="username">SMTP用户名</param>
/// <param name="password">SMTP密码</param>
/// <param name="ssl">是否启用SSL方式</param>
/// <param name="port">SMTP端口</param>
/// <returns></returns>
public static string SendMail(string mailSubjct, string mailBody, string mailFrom, List<string> mailAddress, string hostIp, string username, string password, bool ssl, int port)
{
string error = string.Empty;
try
{
MailMessage mm = new MailMessage();
mm.IsBodyHtml = false;
mm.Subject = mailSubjct;
mm.BodyEncoding = Encoding.UTF8;
mm.Body = mailBody;
mm.IsBodyHtml = true;
mm.From = new MailAddress(mailFrom, Const.SYS_NAME, Encoding.UTF8);
Regex regex = new Regex(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*");
for (int i = 0; i < mailAddress.Count; i++)
{
if (regex.IsMatch(mailAddress[i]))
{
mm.To.Add(mailAddress[i]);
}
}
if (mm.To.Count == 0)
{
return string.Empty;
}
SmtpClient sc = new SmtpClient();
NetworkCredential nc = new NetworkCredential(username, password);
sc.EnableSsl = ssl;
sc.UseDefaultCredentials = false;
sc.Credentials = nc;
sc.DeliveryMethod = SmtpDeliveryMethod.Network;
sc.Host = hostIp;
sc.Port = port;
sc.Send(mm);
}
catch (Exception ex)
{
error = ex.Message;
}
return error;
}
int此行,第二个参数:“mm.From = new MailAddress(mailFrom,Const.SYS_NAME,Encoding.UTF8);”
DisplayName:“Const.SYS_NAME”,我想这就是你想要的。
答案 2 :(得分:0)
我遇到了同样的问题,似乎提供凭据导致服务器使用那些用于'from'名称。
我不得不发表评论:
//client.UseDefaultCredentials = true;
答案 3 :(得分:-1)
您可以设置MailAddress对象的DisplayName属性以设置常规名称,而不是仅使用电子邮件地址。
MailAddress fromAddress = new MailAddress("thedude@lebowski.net");
fromAddress.DisplayName = "The Dude";