在.net中使用SmtpClient发送邮件
我无法使用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我发现在设置
UseDefaultCredentials = false
之前设置 SmtpClient Credentials 属性。UseDefaultCredentials = false
导致凭据被忽略。失败:
有效:
想想吧。
** 更新 **
这里的顺序很重要的原因是
UseDefaultCredentials
属性上的 setter 实际上通过反编译将Credentials
设置为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:
Works:
Go figure.
** UPDATE **
The reason the order is important here is that the setter on the
UseDefaultCredentials
property actually sets theCredentials
tonull
via the decompiled code:简短的回答:不要使用 .net 内部 SMTP 客户端类 - 使用 MailKit。
长答案:
我故意没有复制粘贴此处文档中的示例,因为文档可能会随着时间的推移而发生变化,最好阅读 .
The short answer : Do not use .net the internal SMTP client class - use MailKit.
The long answer :
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 .
这意味着您的邮件服务器不允许邮件中继。您的邮件服务器仅允许您从经过身份验证的电子邮件 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.
试试这个:
Try this :