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

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


评论

没关系,如果您尝试通过SMTP通过Gmail发送邮件,则需要允许安全程度较低的应用访问您的帐户support.google.com/accounts/answer/6010255?hl=zh_CN

#1 楼

mail.Tomail.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);


评论


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

–MRB
2012年2月8日在21:01



那是因为这是一个集合。您可以致电添加

–奥斯卡·凯林(Oskar Kjellin)
2012年2月8日在21:03



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

–MRB
2012年2月8日在21:11



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

–clifford.duke
2013年12月23日在2:04

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

– Mark Miller
2015年4月10日在19:11

#2 楼

This:

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


应为:

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


评论


使用此参数和默认的MailMessage构造函数,您可以设置“收件人”字段而无需设置“发件人”,这将默认为元素(网络设置)中的值

–石碑
16-10-10在22:01

谁能告诉我该如何在我自己的SMTP服务器而不是Google SMTP上使用它?我收到{“无法连接到远程服务器”} {“尝试连接到SMTP服务器时,请求的地址在其上下文中无效IP-ADDRESS:25”}错误

– YuDroid
16 Dec 28'在10:16



@YuDroid正确设置SmtpClient的主机和端口属性。

–密特兰迪尔
16 Dec 28'在15:13

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

– YuDroid
17年1月2日,12:08

#3 楼

终于开始工作了:)

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


很抱歉之前拼写不佳

评论


不应该有mm.Dispose()吗?

–蒸汽
2014年1月3日在22:55

顺便说一句,默认的smtp端口是25。

–蒸汽
2014年1月3日23:26

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

– compski
15年5月24日在18:59

587是安全的SMTP。

–user3800527
18年1月10日在8:21

@ freej17 add MailAddress复制= new MailAddress(“ Notification_List@contoso.com”); mm.CC.Add(copy);

–山姆·斯蒂芬森(Sam Stephenson)
18年7月24日在10:10



#4 楼

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


评论


这根本无法解决OP无法分配给MailMessage属性的原因。

– ProfK
2014年11月9日,12:13

#5 楼

这就是我的工作方式。希望您发现它有用

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月23日在2:50

#6 楼

首先转到https://myaccount.google.com/lesssecureapps,然后将“允许不太安全的应用程序”设为“真”。

,然后使用以下代码。仅当您的发件人电子邮件地址来自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;相同。虽然

–亚历山大
17年7月5日在8:45

#8 楼

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

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


#9 楼

此答案具有以下特点:


尽可能使用“使用”(IDisposable接口)
使用对象初始化程序

异步编程
将SmtpConfig提取到外部类(根据您的需要进行调整)

以下是提取的代码:

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


#10 楼

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
17年1月31日上午10:55

msdn为UseDefaultCredentials属性指出:“如果UseDefaultCredentials属性设置为false,则在连接到服务器时将使用Credentials属性中设置的值作为凭据。”因此,如果您将UseDefaultCredentials属性设置为false,使用了凭据属性(自定义凭据)。

–谢尔盖·伊辛(Sergei Iashin)
17年3月17日在20:28



#11 楼

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;


详细阅读本文

#12 楼

只需尝试以下操作即可:

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


#13 楼

MailKit是一个基于MimeKit的开放源代码跨平台.NET邮件客户端库,针对移动设备进行了优化。
与System.Net.Mail相比,它具有更多,更先进的功能。 MimeKit。

从此处下载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());                
            }


#14 楼

用发送者和接收者的电子邮件地址初始化MailMessage。它应该类似于

string from = "codeforwin@gmail.com";  //Senders email   
string to = "reciever@gmail.com";  //Receiver's email  
MailMessage msg = new MailMessage(from, to); 


阅读有关如何在c#中发送电子邮件的完整代码段。

#15 楼

这也可以。.

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


#16 楼

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


评论


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

– RedBassett
17年2月6日在10:25

@RedBassett感谢您的建议。我刚刚编辑并在注释中添加了一些信息,下次您记住我所说的话时,请记住。

– Dutt93
17年2月6日在11:17

#17 楼

通过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);
        }
    }