1+ import smtplib
2+ from email import encoders
3+ from email .mime .text import MIMEText
4+ from email .mime .multipart import MIMEMultipart
5+ from email .mime .base import MIMEBase
6+ from bs4 import BeautifulSoup as bs
7+
8+ # list of files to send as an attachment to the email
9+ # feel free to add your attachments here
10+ files_to_send = [
11+ "test.txt" ,
12+ "1810.04805.pdf" ,
13+ ]
14+
15+
16+ def send_mail (email , password , FROM , TO , msg ):
17+ # initialize the SMTP server
18+ server = smtplib .SMTP ("smtp.gmail.com" , 587 )
19+ # connect to the SMTP server as TLS mode (secure) and send EHLO
20+ server .starttls ()
21+ # login to the account using the credentials
22+ server .login (email , password )
23+ # send the email
24+ server .sendmail (FROM , TO , msg .as_string ())
25+ # terminate the SMTP session
26+ server .quit ()
27+
28+ # your credentials
29+ 30+ password = "password"
31+
32+ # the sender's email
33+ 34+ # the receiver's email
35+ 36+ # the subject of the email (subject)
37+ subject = "Just a subject"
38+
39+ # initialize the message we wanna send
40+ msg = MIMEMultipart ("alternative" )
41+ # set the sender's email
42+ msg ["From" ] = FROM
43+ # set the receiver's email
44+ msg ["To" ] = TO
45+ # set the subject
46+ msg ["Subject" ] = subject
47+ # set the body of the email as HTML
48+ html = open ("mail.html" ).read ()
49+ # make the text version of the HTML
50+ text = bs (html , "html.parser" ).text
51+
52+ text_part = MIMEText (text , "plain" )
53+ html_part = MIMEText (html , "html" )
54+ # attach the email body to the mail message
55+ # attach the plain text version first
56+ msg .attach (text_part )
57+ msg .attach (html_part )
58+
59+ for file in files_to_send :
60+ # open the file as read in bytes
61+ with open (file , "rb" ) as f :
62+ # read the file content
63+ data = f .read ()
64+ # create the attachement
65+ attach_part = MIMEBase ("application" , "octet-stream" )
66+ attach_part .set_payload (data )
67+ # encode the data to base 64
68+ encoders .encode_base64 (attach_part )
69+ # add the Content-Disposition header
70+ attach_part .add_header ("Content-Disposition" , f"attachment; filename= { file } " )
71+ msg .attach (attach_part )
72+
73+ # send the mail
74+ send_mail (email , password , FROM , TO , msg )
0 commit comments