错误"必须指定收件人"在c#中发送邮件时发生

时间:2016-09-20 11:18:03

标签: c# .net smtp

我正在尝试在c#中发送带有多个附件的邮件,但我收到此错误

  

发送邮件时必须指定收件人

以下是我发送带附件的邮件的代码

            string to = txtto.Text; //To address        
            string from = "xxx@mail.com"; //From address     

            MailMessage message = new MailMessage();
            message.From = new MailAddress(from);


            if (fileuploading.HasFile)//Attaching document    
            {
                string FileNamess = fileuploading.PostedFile.FileName;
                string FileName = Path.GetFileName(fileuploading.PostedFile.FileName);


                message.Attachments.Add(new System.Net.Mail.Attachment(fileuploading.PostedFile.InputStream,FileName));

            }

            string mailbody = editor.Text;
            message.Subject = txtsubject.Text;
            message.Body = mailbody;
            message.BodyEncoding = Encoding.UTF8;
            message.IsBodyHtml = true;


            SmtpClient client = new SmtpClient("smtp.gmail.com", 587); //Gmail smtp        
            System.Net.NetworkCredential basicCredential1 = new
            System.Net.NetworkCredential("xxx@mail.com","xxxxx");
            client.EnableSsl = true;
            client.UseDefaultCredentials = false;
            client.Credentials = basicCredential1;

            try
            {
                client.Send(message);
            }

            catch (Exception ex)
            {
                throw ex;
            }

1 个答案:

答案 0 :(得分:3)

你有一个未使用的字符串“to”。您需要将此字符串添加到收件人列表message.To

为此,请参阅以下摘录;

string to = txtto.Text; //To address        
string from = "xxx@mail.com"; //From address     

MailMessage message = new MailMessage();
message.From = new MailAddress(from);
message.To.Add(to);     //Add this line to your code

要使上述示例正常工作,您的字符串to应包含格式为“xxx@mail.com”的收件人地址。