问题描述
我正在使用一个使用 System.Net.Mail
的简单邮件发件人类.我需要更新我的应用程序,以便各种用户可以通过它发送电子邮件(使用相同的 smtp 帐户),但发件人"地址应该是导致它被发送的用户.我尝试设置 MailMessage
的 From
属性,并将发件人地址发送到 MailMessage
的构造函数,但这些都起作用了.我确定我遗漏了一些简单的东西或不了解邮件 API 的工作原理.有人可以帮忙吗?
I am using a simple mail sender class that uses the System.Net.Mail
. I need to update my application so various users can send email via it (using the same smtp account) but the "From" address should be of the user who is causing it to be sent. I tried setting the From
property of MailMessage
, and sending the from address into the constructor of MailMessage
but nose of those worked. I am sure I am missing something simple or not understanding how the mail API works. Can anyone help?
这是我的 MailSender 类,它基本上包装了 MailMessage
、NetworkCredential
和 SmtpClient
以提供一个简单的邮件发送接口.
Here my MailSender class that basically wraps the MailMessage
, NetworkCredential
and SmtpClient
to provide one simple mail sending interface.
class MailSender
{
private NetworkCredential credential;
private String SenderAddress;
private SmtpClient client;
public MailSender(String ServerURL, String account, String password, String FromAddress = null, int port = -1, bool UseSSL = true)
{
if (port > 0)
{
client = new SmtpClient(ServerURL, port);
}
else
{
client = new SmtpClient(ServerURL);
}
credential = new NetworkCredential(account, password);
client.UseDefaultCredentials = false;
client.EnableSsl = UseSSL;
client.Credentials = credential;
if (FromAddress != null)
{
SenderAddress = FromAddress;
}
else
{
SenderAddress = account;
}
}
public bool SendMessage(String to, String subject, String body)
{
try
{
MailMessage message = new MailMessage(SenderAddress, to, subject, body);
message.From = new MailAddress(SenderAddress, "tester");
message.IsBodyHtml = true;
client.Send(message);
}
catch
{
return false;
}
return true;
}
}
推荐答案
我刚刚通过另一个 SMTP 服务器测试找到了答案.这实际上是由 GMail 不允许任何其他地址引起的.这适用于其他 SMTP 服务器.
I just found out the answer by testing with another SMTP server. This is actually caused by GMail not allowing any other from address. This works fine with other SMTP servers.
感谢 leppie、Mikael Svenson 和 smirkingman 的建议.
Thanks to leppie, Mikael Svenson and smirkingman for their suggestions.
这篇关于设置不同的“发件人"使用 C# 通过 Gmail 发送的邮件的地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!