C# WPF 发送邮件 - 使用 SmtpClient 实现邮件发送
在 C# WPF 中发送邮件,可以使用 'SmtpClient' 类来实现。以下是一个简单的示例代码:
using System;
using System.Net;
using System.Net.Mail;
using System.Windows;
namespace WpfApp
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void SendEmailButton_Click(object sender, RoutedEventArgs e)
{
try
{
string fromEmail = 'sender@example.com';
string toEmail = 'recipient@example.com';
string subject = 'Test Email';
string body = 'This is a test email.';
SmtpClient smtpClient = new SmtpClient('smtp.example.com', 587);
smtpClient.EnableSsl = true;
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = new NetworkCredential('username', 'password');
MailMessage mailMessage = new MailMessage(fromEmail, toEmail, subject, body);
smtpClient.Send(mailMessage);
MessageBox.Show('Email sent successfully.');
}
catch (Exception ex)
{
MessageBox.Show('Failed to send email: ' + ex.Message);
}
}
}
}
在上面的示例代码中,需要将 'fromEmail' 和 'toEmail' 替换为实际的发件人和收件人电子邮件地址。同时,需要填写实际的 SMTP 服务器地址、端口号、登录用户名和密码。
注意:为了使用 'SmtpClient' 类发送电子邮件,需要在项目中添加对 'System.Net' 和 'System.Net.Mail' 命名空间的引用。
原文地址: https://www.cveoy.top/t/topic/o09s 著作权归作者所有。请勿转载和采集!