在.net中使用SmtpClient发送邮件

发布于 2024-08-25 19:33:22 字数 775 浏览 1 评论 0原文

我无法使用 smtp 客户端发送邮件。 这是代码:

SmtpClient client=new SmtpClient("Host");
client.Credentials=new NetworkCredential("username", "password");
MailMessage mailMessage = new MailMessage();
mailMessage.from="[email protected]";
mailMessage.To.Add("[email protected]");
mailMessage.body="body";
mailMessage.subject="subject";
client.Send(mailMessage);

问题是,当我在 ASP.NET 应用程序中使用此代码时,我没有收到任何邮件。当我在 asp.net 中将发件人邮件地址更改为 NetworkCredential 中给出的用户名时,我会收到邮件。

但在 C# Windows 应用程序中,即使发件人的电子邮件地址无效,我也可以收到电子邮件。

I am unable to send the mail using smtp client.
here is the code:

SmtpClient client=new SmtpClient("Host");
client.Credentials=new NetworkCredential("username", "password");
MailMessage mailMessage = new MailMessage();
mailMessage.from="[email protected]";
mailMessage.To.Add("[email protected]");
mailMessage.body="body";
mailMessage.subject="subject";
client.Send(mailMessage);

The problem is that when I use this code in ASP.NET application, I do not receive any mails. When in asp.net I change the from mail address to username given in NetworkCredential, I receive mails.

But in C# windows application, I can get emails, even if sender's email address is not valid.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

天煞孤星 2024-09-01 19:33:22

我发现在设置 UseDefaultCredentials = false 之前设置 SmtpClient Credentials 属性。 UseDefaultCredentials = false 导致凭据被忽略。

失败:

SmtpClient smtp = new SmtpClient;
smtp.Credentials = new NetworkCredential("user","pass");
smtp.UseDefaultCredentials = false;

有效:

SmtpClient smtp = new SmtpClient;
smtp.UseDefaultCredentials = false;
smtp.Credentials = new NetworkCredential("user","pass");

想想吧。

** 更新 **

这里的顺序很重要的原因是 UseDefaultCredentials 属性上的 setter 实际上通过反编译将 Credentials 设置为 null代码:

/// <summary>Gets or sets a <see cref="T:System.Boolean" /> value that controls whether the <see cref="P:System.Net.CredentialCache.DefaultCredentials" /> are sent with requests.</summary>
/// <returns>
/// <see langword="true" /> if the default credentials are used; otherwise <see langword="false" />. The default value is <see langword="false" />.</returns>
/// <exception cref="T:System.InvalidOperationException">You cannot change the value of this property when an e-mail is being sent.</exception>
public bool UseDefaultCredentials
{
  get
  {
    return this.transport.Credentials is SystemNetworkCredential;
  }
  set
  {
    if (this.InCall)
      throw new InvalidOperationException(SR.GetString("SmtpInvalidOperationDuringSend"));
    this.transport.Credentials = value ? (ICredentialsByHost) CredentialCache.DefaultNetworkCredentials : (ICredentialsByHost) null;
  }
}

I figured out that setting the SmtpClient Credentials property before setting the <html><span class="diff-delete">UseDefaultCredentials = false</span></html>. UseDefaultCredentials = false causes the credentials to be ignored.

Fails:

SmtpClient smtp = new SmtpClient;
smtp.Credentials = new NetworkCredential("user","pass");
smtp.UseDefaultCredentials = false;

Works:

SmtpClient smtp = new SmtpClient;
smtp.UseDefaultCredentials = false;
smtp.Credentials = new NetworkCredential("user","pass");

Go figure.

** UPDATE **

The reason the order is important here is that the setter on the UseDefaultCredentials property actually sets the Credentials to null via the decompiled code:

/// <summary>Gets or sets a <see cref="T:System.Boolean" /> value that controls whether the <see cref="P:System.Net.CredentialCache.DefaultCredentials" /> are sent with requests.</summary>
/// <returns>
/// <see langword="true" /> if the default credentials are used; otherwise <see langword="false" />. The default value is <see langword="false" />.</returns>
/// <exception cref="T:System.InvalidOperationException">You cannot change the value of this property when an e-mail is being sent.</exception>
public bool UseDefaultCredentials
{
  get
  {
    return this.transport.Credentials is SystemNetworkCredential;
  }
  set
  {
    if (this.InCall)
      throw new InvalidOperationException(SR.GetString("SmtpInvalidOperationDuringSend"));
    this.transport.Credentials = value ? (ICredentialsByHost) CredentialCache.DefaultNetworkCredentials : (ICredentialsByHost) null;
  }
}
π浅易 2024-09-01 19:33:22

简短的回答:不要使用 .net 内部 SMTP 客户端类 - 使用 MailKit

长答案:

  1. 它被标记为 MS 文档中已过时

[System.Obsolete("SmtpClient 及其网络类型设计不佳,我们强烈建议您使用 https:// /github.com/jstedfast/MailKithttps://github.com/jstedfast/MimeKit 相反")]
公共类SmtpClient:IDisposable

  1. 使用 oss lib MailKit
  2. 阐述:因为你迟早会面对它的缺陷。 在此处阅读或在互联网上阅读。
  3. 以下是发送普通消息和多部分消息。

我故意没有复制粘贴此处文档中的示例,因为文档可能会随着时间的推移而发生变化,最好阅读 .

The short answer : Do not use .net the internal SMTP client class - use MailKit.

The long answer :

  1. It is marked as obsolete in MS docs

[System.Obsolete("SmtpClient and its network of types are poorly designed, we strongly recommend you use https://github.com/jstedfast/MailKit and https://github.com/jstedfast/MimeKit instead")]
public class SmtpClient : IDisposable

  1. Use the oss lib MailKit.
  2. Elaboration : Because you will face its deficiencies sooner rather than later. Read here or read around the internet.
  3. Here is an example for sending plain messages and multipart messages.

I intentionally did not copy-paste the examples from the docs here because the documentation may change over time and it is better to read .

ぃ双果 2024-09-01 19:33:22

这意味着您的邮件服务器不允许邮件中继。您的邮件服务器仅允许您从经过身份验证的电子邮件 ID 作为用户名发送邮件。一般来说,这样做是为了防止邮件以经过验证的身份之外的其他身份发送。

It means your mail server does not allow Mail-Relay. Your mail server only allows you to send mail from authenticated email-id as username. Generally this is done to prevent mails being sent as different identities other than the authenticated one.

装迷糊 2024-09-01 19:33:22

试试这个:

MailMessage mail = new MailMessage("emailfrom","emailto");

mail.From = new MailAddress("emailfrom");
mail.Subject = txtsbjct.Text;
string Body = txtmsg.Text;
mail.Body = Body;

mail.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com"; //Or Your SMTP Server Address
smtp.Credentials = new System.Net.NetworkCredential("youremail", "yourpassword");

smtp.EnableSsl = true;
smtp.Send(mail);
txtemail.Text = "";
txtmsg.Text = "";
txtsbjct.Text = "";
Label1.Text = "your email has been send";
mail = null;
smtp = null;

Try this :

MailMessage mail = new MailMessage("emailfrom","emailto");

mail.From = new MailAddress("emailfrom");
mail.Subject = txtsbjct.Text;
string Body = txtmsg.Text;
mail.Body = Body;

mail.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com"; //Or Your SMTP Server Address
smtp.Credentials = new System.Net.NetworkCredential("youremail", "yourpassword");

smtp.EnableSsl = true;
smtp.Send(mail);
txtemail.Text = "";
txtmsg.Text = "";
txtsbjct.Text = "";
Label1.Text = "your email has been send";
mail = null;
smtp = null;
素年丶 2024-09-01 19:33:22
void sendEmail(string strFrom
                        , string strTo
                        , string strSubject
                        , string strBody)
   {

       MailMessage objMailMessage = new MailMessage();
       System.Net.NetworkCredential objSMTPUserInfo =
           new System.Net.NetworkCredential();
       SmtpClient objSmtpClient = new SmtpClient();

       try
       {
           objMailMessage.From = new MailAddress(strFrom);
           objMailMessage.To.Add(new MailAddress(strTo));
           objMailMessage.Subject = strSubject;
           objMailMessage.Body = strBody;

           objSmtpClient = new SmtpClient("172.0.0.1"); /// Server IP
           objSMTPUserInfo = new System.Net.NetworkCredential
           ("User name", "Password","Domain");
           objSmtpClient.Credentials = objSMTPUserInfo;
           objSmtpClient.UseDefaultCredentials = false;
           objSmtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;

           objSmtpClient.Send(objMailMessage);
       }
       catch (Exception ex)
       { throw ex; }

       finally
       {
           objMailMessage = null;
           objSMTPUserInfo = null;
           objSmtpClient = null;
       }
   }
void sendEmail(string strFrom
                        , string strTo
                        , string strSubject
                        , string strBody)
   {

       MailMessage objMailMessage = new MailMessage();
       System.Net.NetworkCredential objSMTPUserInfo =
           new System.Net.NetworkCredential();
       SmtpClient objSmtpClient = new SmtpClient();

       try
       {
           objMailMessage.From = new MailAddress(strFrom);
           objMailMessage.To.Add(new MailAddress(strTo));
           objMailMessage.Subject = strSubject;
           objMailMessage.Body = strBody;

           objSmtpClient = new SmtpClient("172.0.0.1"); /// Server IP
           objSMTPUserInfo = new System.Net.NetworkCredential
           ("User name", "Password","Domain");
           objSmtpClient.Credentials = objSMTPUserInfo;
           objSmtpClient.UseDefaultCredentials = false;
           objSmtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;

           objSmtpClient.Send(objMailMessage);
       }
       catch (Exception ex)
       { throw ex; }

       finally
       {
           objMailMessage = null;
           objSMTPUserInfo = null;
           objSmtpClient = null;
       }
   }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文