提问人:Francesco Vargas 提问时间:11/3/2023 最后编辑:Francesco Vargas 更新时间:11/6/2023 访问量:44
在 C 上使用 WPF 控制台发送电子邮件#
Send email with WPF Console on C#
问:
我正在尝试在 C# (.NET 6.0) 上构建 WPF 应用程序。 这个应用程序必须发送邮件。我给出的参数是:mailFrom、mailTo、host、password、subject 和邮件正文。响应按钮“发送”的类是这样的:
public partial class MainWindow : Window
{
private readonly ILogger<MainWindow> _logger;
public MainWindow()
{
InitializeComponent();
}
public MainWindow(ILogger<MainWindow> logger) : this()
{
_logger = logger;
}
private void btnSender_Click(object sender, RoutedEventArgs e)
{
MessageRequest mailRequest = new MessageRequest();
var builder = new BodyBuilder();
mailRequest.ToEmail = tbReceiver.Text;
mailRequest.FromEmail = tbSender.Text;
mailRequest.Subject = tbSubject.Text;
mailRequest.Body = tbMessage.Text;
mailRequest.Host = tbHost.Text;
SendMail(mailRequest, builder);
}
private void SendMail(MessageRequest mailRequest, BodyBuilder builder)
{
var email = new MimeMessage();
email.From.Add(MailboxAddress.Parse(mailRequest.FromEmail));
email.To.Add(MailboxAddress.Parse(mailRequest.ToEmail));
email.Subject = mailRequest.Subject;
email.Sender = MailboxAddress.Parse(mailRequest.FromEmail);
builder.HtmlBody = mailRequest.Body;
email.Body = builder.ToMessageBody();
using var smtp = new SmtpClient();
smtp.CheckCertificateRevocation = false;
smtp.Connected += Smtp_Connected;
smtp.Authenticated += Smtp_Authenticated;
smtp.Disconnected += Smtp_Disconnected;
smtp.MessageSent += Smtp_MessageSent;
if (!IsValidEmail(email.From.ToString()) || !IsValidEmail(email.To.ToString()))
{
_logger.LogError("ERROR: Mail not valid.");
}
else
{
smtp.Connect(mailRequest.Host, 587, SecureSocketOptions.StartTls);
if (true)
{
smtp.Authenticate(email.From.ToString(), "XXX");
}
smtp.Send(email);
}
smtp.Disconnect(true);
}
private void Smtp_MessageSent(object? sender, MessageSentEventArgs e)
{
_logger.LogTrace("Message sent {message}. Response: {response}", e.Message, e.Response);
}
private void Smtp_Disconnected(object? sender, DisconnectedEventArgs e)
{
_logger.LogTrace("Disconnected to SMTP {host}", e.Host);
}
private void Smtp_Authenticated(object? sender, AuthenticatedEventArgs e)
{
_logger.LogTrace("Authenticated to SMTP host");
}
private void Smtp_Connected(object? sender, ConnectedEventArgs e)
{
_logger.LogTrace("Connected to SMTP {host}", e.Host);
}
private bool IsValidEmail(string email)
{
try
{
var mailAddress = new System.Net.Mail.MailAddress(email);
return mailAddress.Address == email;
}
catch
{
return false;
}
}
}
但它返回以下错误: 'System.ArgumentNullException: 'Value 不能为 null。Arg_ParamName_Name'。我发现问题出在记录器不起作用并返回此错误。我注释代码行:smtp.Connected += Smtp_Connected; smtp.Authenticated += Smtp_Authenticated; smtp.Disconnected += Smtp_Disconnected; smtp.MessageSent += Smtp_MessageSent;
现在它起作用了。但是,如果我编写相同的代码,但仅适用于 Web API,如果我不注释这些行,它也可以工作。解决方案是什么?
答: 暂无答案
评论
System.Net.Mail.SmtpClient
l_host
tbHost