1 import smtplib
2 from email import encoders
3 from email.mime.base import MIMEBase
4 from email.mime.multipart import MIMEMultipart
5 from email.mime.text import MIMEText
6
7 smtp_server = "localhost"
8 smtp_port = 2525
9 from_email = "you@example.com"
10 to_email = "to@example.com"
11 subject = "Test Email"
12 body = "This is a test email sent to my local SMTP server on port 2525."
13 html_body = "<html><body>This is a HTML</body></html>"
14
15 # Create the email
16 message = MIMEMultipart()
17 message["From"] = from_email
18 message["To"] = to_email
19 message["Subject"] = subject
20
21 message.attach(MIMEText(body, "plain"))
22 message.attach(MIMEText(html_body, "html"))
23
24 # to add an attachment:
25 file_path = "myfile.txt"
26 with open(file_path, "rb") as attachment:
27 part = MIMEBase("application", "octet-stream")
28 part.set_payload(attachment.read())
29 encoders.encode_base64(part)
30 part.add_header(
31 "Content-Disposition",
32 f"attachment; filename= {file_path}",
33 )
34 message.attach(part)
35
36 # Send the email
37 try:
38 with smtplib.SMTP(smtp_server, smtp_port) as server:
39 _ = server.starttls()
40 _ = server.sendmail(from_email, to_email, message.as_string())
41 print("Email sent successfully")
42 except Exception as e:
43 print(f"Failed to send email: {e}")