我正在使用C#,我正在尝试从网页发送电子邮件。我正在尝试从文本框中填充来自电子邮件地址,并且正在对电子邮件地址进行硬编码。我的代码如下,我得到的错误是在代码之后。
try
{
MailMessage oMsg = new MailMessage();
// TODO: Replace with sender e-mail address. Get from textbox: string SenderEmail = emailbox.text
oMsg.From = emailbox.Text; //Senders email
// TODO: Replace with recipient e-mail address.
oMsg.To = "DummyRecipient@gmail.com"; //Recipient email
oMsg.Subject = subjecttbox.Text; //Subject of email
// SEND IN HTML FORMAT (comment this line to send plain text).
//oMsg.BodyFormat = MailFormat.Html;
// HTML Body (remove HTML tags for plain text).
oMsg.Body = EmailBody; //Body of the email
// ADD AN ATTACHMENT.
// TODO: Replace with path to attachment.
//String sFile = @"C:\temp\Hello.txt";
//MailAttachment oAttch = new MailAttachment(sFile, MailEncoding.Base64);
//oMsg.Attachments.Add(oAttch);
// TODO: Replace with the name of your remote SMTP server.
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
//SmtpMail.SmtpServer = "Smtp.gmail.com"; //Email server name, Gmail = Smtp.gmail.com
SmtpServer.Port = 587;
SmtpServer.Credentials = new System.Net.NetworkCredential("DummySenderAddress@gmail.com", "DummyPassword");
SmtpServer.EnableSsl = true;
SmtpMail.Send(oMsg);
oMsg = null;
//oAttch = null;
}
catch //(Exception e)
{
Console.WriteLine("{0} Exception caught.", e);
}
无法隐式转换类型'字符串'至 ' System.Net.Mail.MailAddress'财产或指数 ' System.Net.Mail.MailMessage.To'无法分配 - 它被读取 仅
无法隐式转换类型'字符串'至 ' System.Net.Mail.MailAddressCollection'名称' SmtpMail'才不是 存在于当前背景中
答案 0 :(得分:1)
问题出在您的行中:
oMsg.To = "DummyRecipient@gmail.com"; //Recipient email
电子邮件可以有多个收件人。因此,MailMessage类的“To”属性是一个集合。没有一个电子邮件地址。
此外,您需要创建一个MailAddress对象,而不是仅使用电子邮件的字符串。
使用以下行而不是上述行。
oMsg.To.Add(new MailAddress("DummyRecipient@gmail.com")); //Recipient email
答案 1 :(得分:1)
oMsg.From将MailAddress对象作为其输入,而不是字符串。替换为:
oMsg.From = new MailAddress(emailbox.Text);
oMsg.To将MailAddressCollection作为其输入。假设集合不为null,您应该能够将其替换为:
oMsg.To.Add("DummyRecipient@gmail.com");