为什么在发送SMTP电子邮件时出现“无法分配属性”?


274

我不明白为什么这段代码无法正常工作。我收到一条错误消息,指出无法分配属性

MailMessage mail = new MailMessage();
SmtpClient client = new SmtpClient();            
client.Port = 25;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Host = "smtp.gmail.com";
mail.To = "user@hotmail.com"; // <-- this one
mail.From = "you@yourcompany.com";
mail.Subject = "this is a test email.";
mail.Body = "this is my test email body";
client.Send(mail);

1
诺尔说,如果你想通过SMTP通过Gmail发送你需要允许不够安全的应用访问您的帐户support.google.com/accounts/answer/6010255?hl=en
马修锁定

Answers:


362

mail.To并且mail.From是只读的。将它们移至构造函数。

using System.Net.Mail;

...

MailMessage mail = new MailMessage("you@yourcompany.com", "user@hotmail.com");
SmtpClient client = new SmtpClient();
client.Port = 25;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Host = "smtp.gmail.com";
mail.Subject = "this is a test email.";
mail.Body = "this is my test email body";
client.Send(mail);

9
mail.To是只读的,from不是。公共MailAddressCollection到{get; }
MRB 2012年

41
那是因为这是一个集合。你可以只调用添加到它
奥斯卡Kjellin

17
@Oskar好的,所以我应该更具体一些。您不能将mail.to设置为特定地址。您必须使用构造函数或调用add。我只是在解决第一个编译器警告:错误CS0200:无法将属性或索引器'System.Net.Mail.MailMessage.To'分配给-只读
-MRB

9
@DougHauf可以将SmtpClient类与受密码保护的smtp服务器一起使用。您的smtp服务器似乎是内部服务器,这意味着您的程序只有在网络上时才能够连接到该smtp服务器。 client.Host = "mail.youroutgoingsmtpserver.com"; client.Credentials = new System.Net.NetworkCredential("yourusername", "yourpassword");
2013年

4
SmtpClient实现IDisposable,因此您可能应该将其更改为:using(SmtpClient client = new SmtpClient()){...}
Mark Miller

261

这个 :

mail.To = "user@hotmail.com";

应该:

mail.To.Add(new MailAddress("user@hotmail.com"));

使用此参数和默认MailMessage构造函数,您To无需设置即可设置字段From,默认为<smtp>元素(网络设置)中的值
bstoney

谁能告诉我该如何在我自己的SMTP服务器而不是Google SMTP上使用它?{"Unable to connect to the remote server"} {"The requested address is not valid in its context IP-ADDRESS:25"}当我尝试连接到SMTP服务器时收到错误消息
YuDroid

@YuDroid 正确设置HostPort属性SmtpClient
秘兰迪里

@Mithrandir是的,我设置正确。我已经在Outlook中设置了我的SMTP邮件帐户,并从中获取了所有必要的设置。主机和端口在Web.config文件中声明,我正在获取运行时。
YuDroid

121

终于上班了:)

using System.Net.Mail;
using System.Text;

...

// Command line argument must the the SMTP host.
SmtpClient client = new SmtpClient();
client.Port = 587;
client.Host = "smtp.gmail.com";
client.EnableSsl = true;
client.Timeout = 10000;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Credentials = new System.Net.NetworkCredential("user@gmail.com","password");

MailMessage mm = new MailMessage("donotreply@domain.com", "sendtomyemail@domain.co.uk", "test", "test");
mm.BodyEncoding = UTF8Encoding.UTF8;
mm.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;

client.Send(mm);

抱歉以前拼写不好


5
不应该有mm.Dispose()吗?
2014年

顺便说一句,默认的smtp端口为25。–
Steam

2
谢谢!直到今天,它仍然有效,但改用Outlook。[client.Host =“ smtp-mail.outlook.com”;]
compski

6
587是安全的SMTP。
user3800527

1
@ freej17 add MailAddress复制= new MailAddress(“ Notification_List@contoso.com”); mm.CC.Add(copy);
山姆·斯蒂芬森,

19
public static void SendMail(MailMessage Message)
{
    SmtpClient client = new SmtpClient();
    client.Host = "smtp.googlemail.com";
    client.Port = 587;
    client.UseDefaultCredentials = false;
    client.DeliveryMethod = SmtpDeliveryMethod.Network;
    client.EnableSsl = true;
    client.Credentials = new NetworkCredential("myemail@gmail.com", "password");
    client.Send(Message); 
}

4
这根本没有解决为什么无法将OP分配给MailMessage 属性的问题。
ProfK 2014年

17

这就是我的工作方式。希望你觉得它有用

MailMessage objeto_mail = new MailMessage();
SmtpClient client = new SmtpClient();
client.Port = 25;
client.Host = "smtp.internal.mycompany.com";
client.Timeout = 10000;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Credentials = new System.Net.NetworkCredential("user", "Password");
objeto_mail.From = new MailAddress("from@server.com");
objeto_mail.To.Add(new MailAddress("to@server.com"));
objeto_mail.Subject = "Password Recover";
objeto_mail.Body = "Message";
client.Send(objeto_mail);

在家里,我的计算机上没有内部公司服务器,也没有Outlook.com。我在线有一个Outlook.com帐户,我可以将其用作主持人吗?
Doug Hauf 2013年

12

首先转到https://myaccount.google.com/lesssecureapps,然后将允许不太安全的应用设为true

然后使用下面的代码。仅当您的发件人电子邮件地址来自gmail时,此以下代码才有效。

static void SendEmail()
    {
        string mailBodyhtml =
            "<p>some text here</p>";
        var msg = new MailMessage("from@gmail.com", "to1@gmail.com", "Hello", mailBodyhtml);
        msg.To.Add("to2@gmail.com");
        msg.IsBodyHtml = true;
        var smtpClient = new SmtpClient("smtp.gmail.com", 587); //**if your from email address is "from@hotmail.com" then host should be "smtp.hotmail.com"**
        smtpClient.UseDefaultCredentials = true;
        smtpClient.Credentials = new NetworkCredential("from@gmail.com", "password");
        smtpClient.EnableSsl = true;
        smtpClient.Send(msg);
        Console.WriteLine("Email Sent Successfully");
    }

7

如果您不想让您的电子邮件和密码出现在代码中,并且希望公司电子邮件客户端服务器使用Windows凭据,请在下面使用。

client.Credentials = CredentialCache.DefaultNetworkCredentials;

资源


这与client.UseDefaultCredentials = true;相同。虽然
亚历山大

4

截止到2017年3月,这对我才有效。从上面的解决方案“ Finally got working :)”开始,该解决方案最初并不起作用。

SmtpClient client = new SmtpClient();
client.Port =  587;
client.Host = "smtp.gmail.com";
client.EnableSsl = true;
client.Timeout = 10000;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Credentials = new System.Net.NetworkCredential("<me>@gmail.com", "<my pw>");
MailMessage mm = new MailMessage(from_addr_text, to_addr_text, msg_subject, msg_body);
mm.BodyEncoding = UTF8Encoding.UTF8;
mm.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;

client.Send(mm);

3

该答案具有以下特点:

这是提取的代码:

    public async Task SendAsync(string subject, string body, string to)
    {
        using (var message = new MailMessage(smtpConfig.FromAddress, to)
        {
            Subject = subject,
            Body = body,
            IsBodyHtml = true
        })
        {
            using (var client = new SmtpClient()
            {
                Port = smtpConfig.Port,
                DeliveryMethod = SmtpDeliveryMethod.Network,
                UseDefaultCredentials = false,
                Host = smtpConfig.Host,
                Credentials = new NetworkCredential(smtpConfig.User, smtpConfig.Password),
            })
            {
                await client.SendMailAsync(message);
            }
        }                                     
    }

SmtpConfig类别:

public class SmtpConfig
{
    public string Host { get; set; }
    public string User { get; set; }
    public string Password { get; set; }
    public int Port { get; set; }
    public string FromAddress { get; set; }
}

2
MailMessage mm = new MailMessage(txtEmail.Text, txtTo.Text);
mm.Subject = txtSubject.Text;
mm.Body = txtBody.Text;
if (fuAttachment.HasFile)//file upload select or not
{
    string FileName = Path.GetFileName(fuAttachment.PostedFile.FileName);
    mm.Attachments.Add(new Attachment(fuAttachment.PostedFile.InputStream, FileName));
}
mm.IsBodyHtml = false;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.EnableSsl = true;
NetworkCredential NetworkCred = new NetworkCredential(txtEmail.Text, txtPassword.Text);
smtp.UseDefaultCredentials = true;
smtp.Credentials = NetworkCred;
smtp.Port = 587;
smtp.Send(mm);
Response.write("Send Mail");

观看视频: https : //www.youtube.com/watch?v=bUUNv-19QAI


尽管此视频可以回答问题,但最好在此处包括答案的基本部分并提供参考链接。如果链接的页面发生更改,仅链接的答案可能会失效
afxentios

msdn为UseDefaultCredentials属性声明:“如果UseDefaultCredentials属性设置为false,则在连接到服务器时,将使用Credentials属性中设置的值作为凭据。” ,因此,如果您使用过Credentials属性(自定义凭据),则应将UseDefaultCredentials属性设置为false。
谢尔盖·伊亚辛

1
smtp.Host = "smtp.gmail.com"; // the host name
smtp.Port = 587; //port number
smtp.EnableSsl = true; //whether your smtp server requires SSL
smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
smtp.Credentials = new NetworkCredential(fromAddress, fromPassword);
smtp.Timeout = 20000;

查看本文以获取更多详细信息


1

只需尝试以下方法:

string smtpAddress = "smtp.gmail.com";
int portNumber = 587;
bool enableSSL = true;
string emailFrom = "companyemail";
string password = "password";
string emailTo = "Your email";
string subject = "Hello!";
string body = "Hello, Mr.";
MailMessage mail = new MailMessage();
mail.From = new MailAddress(emailFrom);
mail.To.Add(emailTo);
mail.Subject = subject;
mail.Body = body;
mail.IsBodyHtml = true;
using (SmtpClient smtp = new SmtpClient(smtpAddress, portNumber))
{
   smtp.Credentials = new NetworkCredential(emailFrom, password);
   smtp.EnableSsl = enableSSL;
   smtp.Send(mail);
}

1

MailKit是基于MimeKit的开放源代码跨平台.NET邮件客户端库,并针对移动设备进行了优化。通过MimeKit,它具有比System.Net.Mail Microsoft TNEF支持更好的更多高级功能。

这里下载nuget包

看这个例子你可以发送邮件

            MimeMessage mailMessage = new MimeMessage();
            mailMessage.From.Add(new MailboxAddress(senderName, sender@address.com));
            mailMessage.Sender = new MailboxAddress(senderName, sender@address.com);
            mailMessage.To.Add(new MailboxAddress(emailid, emailid));
            mailMessage.Subject = subject;
            mailMessage.ReplyTo.Add(new MailboxAddress(replyToAddress));
            mailMessage.Subject = subject;
            var builder = new BodyBuilder();
            builder.TextBody = "Hello There";            
            try
            {
                using (var smtpClient = new SmtpClient())
                {
                    smtpClient.Connect("HostName", "Port", MailKit.Security.SecureSocketOptions.None);
                    smtpClient.Authenticate("user@name.com", "password");

                    smtpClient.Send(mailMessage);
                    Console.WriteLine("Success");
                }
            }
            catch (SmtpCommandException ex)
            {
                Console.WriteLine(ex.ToString());              
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());                
            }

1

通过smtp发送电子邮件

public void EmailSend(string subject, string host, string from, string to, string body, int port, string username, string password, bool enableSsl)
    {
        try
        {
            MailMessage mail = new MailMessage();
            SmtpClient smtpServer = new SmtpClient(host);
            mail.Subject = subject;
            mail.From = new MailAddress(from);
            mail.To.Add(to);
            mail.Body = body;
            smtpServer.Port = port;
            smtpServer.Credentials = new NetworkCredential(username, password);
            smtpServer.EnableSsl = enableSsl;
            smtpServer.Send(mail);
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);
        }
    }


0

这也会工作..

string your_id = "your_id@gmail.com";
string your_password = "password";
try
{
   SmtpClient client = new SmtpClient
   {
     Host = "smtp.gmail.com",
     Port = 587,
     EnableSsl = true,
     DeliveryMethod = SmtpDeliveryMethod.Network,
     Credentials = new System.Net.NetworkCredential(your_id, your_password),
     Timeout = 10000,
   };
   MailMessage mm = new MailMessage(your_iD, "recepient@gmail.com", "subject", "body");
   client.Send(mm);
   Console.WriteLine("Email Sent");
 }
 catch (Exception e)
 {
   Console.WriteLine("Could not end email\n\n"+e.ToString());
 }

0
 //Hope you find it useful, it contain too many things

    string smtpAddress = "smtp.xyz.com";
    int portNumber = 587;
    bool enableSSL = true;
    string m_userName = "support@xyz.com";
    string m_UserpassWord = "56436578";

    public void SendEmail(Customer _customers)
    {
        string emailID = gghdgfh@gmail.com;
        string userName = DemoUser;

        string emailFrom = "qwerty@gmail.com";
        string password = "qwerty";
        string emailTo = emailID;

        // Here you can put subject of the mail
        string subject = "Registration";
        // Body of the mail
        string body = "<div style='border: medium solid grey; width: 500px; height: 266px;font-family: arial,sans-serif; font-size: 17px;'>";
        body += "<h3 style='background-color: blueviolet; margin-top:0px;'>Aspen Reporting Tool</h3>";
        body += "<br />";
        body += "Dear " + userName + ",";
        body += "<br />";
        body += "<p>";
        body += "Thank you for registering </p>";            
        body += "<p><a href='"+ sURL +"'>Click Here</a>To finalize the registration process</p>";
        body += " <br />";
        body += "Thanks,";
        body += "<br />";
        body += "<b>The Team</b>";
        body += "</div>";
       // this is done using  using System.Net.Mail; & using System.Net; 
        using (MailMessage mail = new MailMessage())
        {
            mail.From = new MailAddress(emailFrom);
            mail.To.Add(emailTo);
            mail.Subject = subject;
            mail.Body = body;
            mail.IsBodyHtml = true;
            // Can set to false, if you are sending pure text.

            using (SmtpClient smtp = new SmtpClient(smtpAddress, portNumber))
            {
                smtp.Credentials = new NetworkCredential(emailFrom, password);
                smtp.EnableSsl = enableSSL;
                smtp.Send(mail);
            }
        }
    }

2
请考虑使用您的答案来解释解决方案,以及为什么原始提问者遇到了问题,而不是简单地张贴代码墙。这对于原始的问询者和将来的访问者来说都将更加有用,以使其首先了解问题的原因。
RedBassett

@RedBassett感谢您的建议。我刚刚编辑并在评论中添加了一些信息,下次您记住我所说的话时,请记住。
Dutt93 '17
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.