指定的字符串不是电子邮件地址所需的格式,不知道出了什么问题
本文关键字:不知道 什么 问题 格式 字符串 电子邮件地址 | 更新日期: 2023-09-27 18:20:04
我知道这个问题已经存在,但我读了所有的问题,没有找到答案。这是我的SendEmail方法。
public bool SendEmail(PostEmail postEmail)
{
if (string.IsNullOrEmpty(postEmail.emailTo))
{
return false;
}
using (SmtpClient smtpClient = new SmtpClient())
{
using (MailMessage message = new MailMessage())
{
message.Subject = postEmail.subject == null ? "" : postEmail.subject;
message.Body = postEmail.body == null ? "" : postEmail.body;
message.IsBodyHtml = postEmail.isBodyHtml;
message.To.Add(new MailAddress(postEmail.emailTo));
try
{
smtpClient.Send(message);
return true;
}
catch (Exception exception)
{
//Log the exception to DB
throw new FaultException(exception.Message);
}
}
}
我有这个错误的问题
指定的字符串不是电子邮件所需的格式地址
我不知道会出什么问题。请帮忙吗?
在线上放置一个断点
message.To.Add(new MailAddress(postEmail.emailTo));
以及当调试器在运行代码时命中行时在中检查电子邮件地址的值postEmail.emailTo
它很可能是错误的格式,这就是产生的原因错误。
这是定义客户端和发送电子邮件的正确方式。定义的完整结构是错误的,这不仅仅是关于emailTo字符串
命名空间App.MYEmailApp.Service{
公共类EmailService:IEmailService{
public void SendEmail(PostEmail postEmail)
{
MailAddress from = new MailAddress(postEmail.emailFrom, postEmail.emailFromName);
MailAddress to = new MailAddress(postEmail.emailTo, postEmail.emailToName);
MailMessage message = new MailMessage(from, to);
message.Subject = postEmail.subject;
message.Body = postEmail.body;
MailAddress bcc = new MailAddress("xxxx@gmail.com");
message.Bcc.Add(bcc);
SmtpClient client = new SmtpClient();
//client.UseDefaultCredentials = false;
//client.Credentials.GetCredential("smtp.xxxx.com", 587, "server requires authentication");
Console.WriteLine("Sending an e-mail message to {0} and {1}.", to.DisplayName, message.Bcc.ToString());
try
{
client.Send(message);
}
catch (Exception ex)
{
Console.WriteLine("Exception caught in CreateBccTestMessage(): {0}",
ex.ToString());
}
}
}
公共类PostEmail{
public string emailTo;
public string emailToName;
public string subject;
public string body;
public string emailFrom;
public string emailFromName;
public bool isBodyHtml;
}
}