-
Notifications
You must be signed in to change notification settings - Fork 0
/
Program.cs
77 lines (62 loc) · 2.48 KB
/
Program.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
66
67
68
69
70
71
72
73
74
75
76
77
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Mail;
using CommandLine;
namespace dotnetcore_test_smtp
{
class Program
{
class Options
{
[Option("server", Required = true, HelpText = "SMTP Server name.")]
public string Server { get; set; }
[Option("port", HelpText = "SMTP Server port number.")]
public int Port { get; set; }
[Option('u', "user", Required = true, HelpText = "Username.")]
public string Username { get; set; }
[Option('p', "pwd", Required = true, HelpText = "Password.")]
public string Password { get; set; }
[Option("to", Required = true, HelpText = "Email To.")]
public string To { get; set; }
[Option("subject", Required = true, HelpText = "Email subject.")]
public string Subject { get; set; }
[Option("body", Required = true, HelpText = "Email body.")]
public string Body { get; set; }
}
static void Main(string[] args)
{
CommandLine.Parser.Default.ParseArguments<Options>(args)
.WithParsed<Options>(opts => RunOptionsAndReturnExitCode(opts))
.WithNotParsed<Options>((errs) => HandleParseError(errs));
}
private static void HandleParseError(IEnumerable<Error> errs)
{
errs.Output();
}
private static void RunOptionsAndReturnExitCode(Options opts)
{
try
{
Console.WriteLine("Preparing message...");
var client = new SmtpClient(opts.Server, opts.Port > 0 ? opts.Port : 25 );
client.EnableSsl = true;
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential(opts.Username, opts.Password);
var mailMessage = new MailMessage();
mailMessage.From = new MailAddress(opts.Username);
mailMessage.To.Add(opts.To);
mailMessage.Subject = opts.Subject;
mailMessage.Body = opts.Body;
client.Send(mailMessage);
Console.WriteLine("Message sent! :)\nCheck your inbox!");
}
catch (Exception ex)
{
Console.WriteLine("Something went wrong!\n");
Console.WriteLine("ERROR:\n");
Console.WriteLine(ex.Message);
}
}
}
}