-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSmtpHelper.cs
65 lines (58 loc) · 1.96 KB
/
SmtpHelper.cs
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
using System;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Text;
namespace ExpressBackup
{
public class Smtp
{
public string
Host,
User,
Password,
Mail;
public int
Port = 25;
}
static class SmtpHelper
{
public static void Send(Smtp smtp, string to, string topic, string body, bool throwException = false)
{
foreach (var mail in (to ?? string.Empty).Split(';').Select(e => e.Trim()).Where(e => e != string.Empty))
SendInternal(smtp, mail, topic, body, throwException);
}
static void SendInternal(Smtp smtp, string to, string topic, string body, bool throwException)
{
using (var mail = new MailMessage(new MailAddress(smtp.Mail), new MailAddress(to)))
{
try
{
mail.ReplyTo = new MailAddress(smtp.Mail);
mail.IsBodyHtml = true;
mail.BodyEncoding = Encoding.UTF8;
mail.Subject = topic;
mail.Body = body;
var
client = new SmtpClient(smtp.Host)
{
DeliveryMethod = SmtpDeliveryMethod.Network,
Port = smtp.Port
};
if (!string.IsNullOrEmpty(smtp.User))
{
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential(smtp.User, smtp.Password);
}
client.Send(mail);
}
catch (Exception ex)
{
Log.Entry(LogSeverity.Error, "failed to send mail to {0}: {1}", to, ex);
if (throwException)
throw;
}
}
}
}
}