--Create a Gmail account --Turn on "Allow insecure apps"
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email import encoders
from email.utils import formatdate
import smtplib
import ssl
if __name__ == '__main__':
#Gmail account information(★ Setting required ★)
mail_username = 'Created Gmail account name'
mail_password = 'Password for the Gmail account you created'
#Email information(★ Change as needed ★)
body = 'This is the text.'
subject = 'This is the title.'
to_addrs = ['[email protected]', '[email protected]'] #Address list sent
attach_files = ['aaa.zip'] #Set the local file name you want to attach
_msg = MIMEMultipart()
_msg['From'] = mail_username
_msg['To'] = "; ".join(to_addrs)
_msg['Subject'] = subject
_msg['Date'] = formatdate(timeval=None, localtime=True)
#Add text
_msg.attach(MIMEText(body, "plain"))
#Add attachment
for filename in attach_files:
with open(filename, 'rb') as _f:
part = MIMEBase('application', 'octet-stream')
part.set_payload(_f.read())
# base64 encode
encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename= {}'.format(filename))
_msg.attach(part)
#Send over secure SSL connection
context = ssl.create_default_context()
_smtp = smtplib.SMTP_SSL(host='smtp.gmail.com', port=465, timeout=10, context=context)
_smtp.login(user=mail_username, password=mail_password)
_smtp.sendmail(mail_username, to_addrs, _msg.as_string())
_smtp.close()
Recommended Posts