Code · 95 lines · 2020 bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95using System.Net;
using System.Net.Mail;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.StartPanel;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.Tab;

namespace MailSharp.TestFormApp
{
	public partial class Form1 : Form
	{
		private CancellationTokenSource? cts;
		public Form1()
		{
			InitializeComponent();
		}

		private void UseCrendentials_CheckedChanged(object sender, EventArgs e)
		{
			this.grpCredentials.Enabled = this.chkUseCredentials.Checked;
		}

		private async void SendEmail_Click(object sender, EventArgs e)
		{
			this.button1.Enabled = false;
			this.button2.Enabled = true;
			this.grpEmail.Enabled = false;

			cts = new CancellationTokenSource();

			try
			{
				await SendEmailAsync(cts.Token);

			}
			catch(OperationCanceledException)
			{
				//MessageBox.Show("Email sending was cancelled.");
			}
			catch (Exception ex)
			{
				MessageBox.Show($"An error occurred: {ex.Message}");
			}
			finally
			{
				this.button1.Enabled = true;
				this.button2.Enabled = false;
				this.grpEmail.Enabled = true;
			}
		}

		private void Cancel_Click(object sender, EventArgs e)
		{
			if (this.cts is not null && !this.cts.IsCancellationRequested)
			{
				this.cts.Cancel();
			}
		}

		private async Task SendEmailAsync(CancellationToken ct)
		{
			int smtpPort = 25;
			if(rad1.Checked)
			{
				smtpPort = 25;
			}
			else if(rad2.Checked)
			{
				smtpPort = 465;
			}
			else if(rad3.Checked)
			{
				smtpPort = 587;
			}

			using SmtpClient client = new(this.txtServer.Text, smtpPort);

			if(chkUseCredentials.Checked)
				client.Credentials = new NetworkCredential(this.txtUserid.Text, this.txtPassword.Text);

			if(this.chkEnableSSL.Checked)
				client.EnableSsl = true;

			MailMessage message = new()
			{
				From = new MailAddress(this.txtFrom.Text),
				Subject = this.txtSubject.Text,
				Body = this.txtBody.Text,
				IsBodyHtml = false
			};
			message.To.Add(this.txtTo.Text);

			await client.SendMailAsync(message, ct);
		}

	}
}