-
Notifications
You must be signed in to change notification settings - Fork 1
/
smtp_auth_test.py
77 lines (66 loc) · 2.17 KB
/
smtp_auth_test.py
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
import argparse
import sys
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument(
'-H', '--host', required=True,
type=str)
parser.add_argument(
'-P', '--port', required=False,
type=int, default=25)
parser.add_argument(
'-u', '--username', required=True,
type=str)
parser.add_argument(
'-p', '--password', required=True,
type=str)
parser.add_argument(
'-r', '--recipient', required=False, type=str,
help="Recipient email, defaults to the username if not provided")
parser.add_argument(
'-s', '--sender', required=False, type=str,
help="Sender email, defaults to the username if not provided")
parser.add_argument(
'--no-login', required=False,
action='store_true',
help="Do not authenticate")
parser.add_argument(
'--no-tls', required=False,
action='store_true',
help="Do not use TLS")
# If no arguments are provided, print help
if len(sys.argv) == 1:
parser.print_help()
sys.exit(1)
else:
return parser.parse_args()
def send_email(host, port, username, password, sender, recipient, no_tls,
no_login):
if not sender:
sender = username
if not recipient:
recipient = username
subject = 'Test Email'
body = 'Test body'
msg = MIMEMultipart()
msg['From'] = sender
msg['To'] = recipient
msg['Subject'] = subject
msg.attach(MIMEText(body, 'plain'))
try:
with smtplib.SMTP(host, port) as server:
if not no_tls:
server.starttls()
if not no_login:
server.login(username, password)
server.sendmail(sender, recipient, msg.as_string())
print("Email sent successfully.")
except Exception as e:
print(f"Failed to send email: {e}")
if __name__ == "__main__":
args = parse_args()
send_email(args.host, args.port, args.username, args.password, args.sender,
args.recipient, args.no_tls, args.no_login)