Odosielanie e-mailov s prílohou v Pythone cez SMTP

V tomto návode si predstavíme modul v Pythone, ktorý sa používa pre odosielanie e-mailov. Taktiež si ukážeme ako odosielať jednoduché textové e-maily, e-maily s prílohami.

#####################################################################
#       Script to send an email with multiple attachments           #
#                   Script by: Lakshay Arora                        #
#                    Dated: January 1, 2016                         #
#####################################################################

# This script uses a gmail account to send the mail. If you
# have your account with another email provider, you will have
# to change the smtp_variable and smtp_port variable accordingly.

import smtplib, os
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email import encoders

# fill in the variables
smtp_server = "smtp.gmail.com"
smtp_port = 587 # for smtp.gmail.com
from_address = "from_address_here" # e.g. username@gmail.com
from_password = "from_address_password_here" # required by script to login using your username
to_address = "to_address_here" # e.g. username2@gmail.com
subject = "Subject_here"
mail_body = "Body content here"
attachment_1 = r"absolute_path_of_file_1" # e.g. file = r"C:\Folder1\text1.txt" # if you attach more than two files here, be sure to append them to the files dictionary below, as done for attachemnt_1 and attachment_2.
attachment_2 = r"absolute_path_of_file_2"

msg = MIMEMultipart()
msg['Subject'] = subject
msg['To'] = to_address
msg.attach(MIMEText(mail_body))

files = []
files.append(attachment_1)
files.append(attachment_2)
for file in files:
part = MIMEBase('application', "octet-stream")
part.set_payload(open(file, "rb").read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="{0}"'.format(os.path.basename(file)))
msg.attach(part)

server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls()
server.login(from_address, from_password)
server.sendmail(from_address, to_address, msg.as_string())
server.quit()
##

zdroj: https://idomaster.com/solutions/sending-a-mail-with-attachments-via-smtplib-email-modules

Loading Facebook Comments ...