在.net中使用SmtpClient发送邮件

编程入门 行业动态 更新时间:2024-10-27 07:28:22
本文介绍了在中使用SmtpClient发送邮件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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="sender@gmail"; mailMessage.To.Add("recipient@gmail"); mailMessage.body="body"; mailMessage.subject="subject"; client.Send(mailMessage);

问题是当我在ASP.NET应用程序中使用此代码时,我没有收到任何邮件.在asp中,我将邮件地址从NetworkCredential中指定的用户名更改为我的邮件.

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

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

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

推荐答案

我发现在设置'UseDefaultCredentials = false'之前设置SmtpClient Credentials属性 UseDefaultCredentials = false 会使凭据被忽略.

I figured out that setting the SmtpClient Credentials property before setting the ' UseDefaultCredentials = false ' UseDefaultCredentials = false causes the credentials to be ignored.

失败:

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 :

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; } }

更多推荐

在.net中使用SmtpClient发送邮件

本文发布于:2023-08-07 10:22:04,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1318594.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:发送邮件   net   SmtpClient

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!