设置不同的“发件人"使用 C# 通过 Gmail 发送的邮件的地址 [英] Setting a different "From" address for mail sent via Gmail using C#

查看:18
本文介绍了设置不同的“发件人"使用 C# 通过 Gmail 发送的邮件的地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一个使用 System.Net.Mail 的简单邮件发件人类.我需要更新我的应用程序,以便各种用户可以通过它发送电子邮件(使用相同的 smtp 帐户),但发件人"地址应该是导致它被发送的用户.我尝试设置 MailMessageFrom 属性,并将发件人地址发送到 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 类,它基本上包装了 MailMessageNetworkCredentialSmtpClient 以提供一个简单的邮件发送接口.

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 发送的邮件的地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆