|
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
|
smtp_username = "your_username" # Add your SMTP username here |
|
10
|
smtp_password = "your_password" # Add your SMTP password here |
|
11
|
|
|
12
|
from_email = "you@example.com" |
|
13
|
to_email = "to@example.com" |
|
14
|
subject = "Test Email" |
|
15
|
body = "This is a test email sent to my local SMTP server on port 2525." |
|
16
|
html_body = "<html><body>This is a HTML</body></html>" |
|
17
|
|
|
18
|
# Create the email |
|
19
|
message = MIMEMultipart() |
|
20
|
message["From"] = from_email |
|
21
|
message["To"] = to_email |
|
22
|
message["Subject"] = subject |
|
23
|
|
|
24
|
message.attach(MIMEText(body, "plain")) |
|
25
|
message.attach(MIMEText(html_body, "html")) |
|
26
|
|
|
27
|
# to add an attachment: |
|
28
|
file_path = "myfile.txt" |
|
29
|
with open(file_path, "rb") as attachment: |
|
30
|
part = MIMEBase("application", "octet-stream") |
|
31
|
part.set_payload(attachment.read()) |
|
32
|
encoders.encode_base64(part) |
|
33
|
part.add_header( |
|
34
|
"Content-Disposition", |
|
35
|
f"attachment; filename= {file_path}", |
|
36
|
) |
|
37
|
message.attach(part) |
|
38
|
|
|
39
|
# Send the email |
|
40
|
try: |
|
41
|
with smtplib.SMTP(smtp_server, smtp_port) as server: |
|
42
|
_ = server.starttls() |
|
43
|
_ = server.login( |
|
44
|
smtp_username, smtp_password |
|
45
|
) # Add this line for authentication |
|
46
|
_ = server.sendmail(from_email, to_email, message.as_string()) |
|
47
|
print("Email sent successfully") |
|
48
|
except Exception as e: |
|
49
|
print(f"Failed to send email: {e}") |