Вложение некоторых файлов в составную электронную почту MIME - PullRequest
0 голосов
/ 02 ноября 2018

Как я могу прикрепить некоторые файлы к электронной почте MIME, используя Python3? Я хочу отправить некоторые вложения в виде «загружаемого контента» на мою HTML-почту (с резервным текстом в виде простого текста). Пока ничего не смог найти ...

Редактировать: после нескольких попыток я просто отправил файл. Спасибо за совет @ tripleee . Но, к сожалению, мой HTML теперь отправляется в виде простого текста ...

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.utils import formatdate
from os.path import basename
import smtplib

login = "*********"
password = "*********"
server = "smail.*********:25"
files = ['Anhang/file.png']

# Create the root message and fill in the from, to, and subject headers
msg = MIMEMultipart('related')
msg['From'] = "*********"
msg['To'] = "*********"
msg['Date'] = formatdate(localtime=True)
msg['Subject'] = "*********"
msg['Reply-To'] = "*********"
msg.preamble = 'This is a multi-part message in MIME format.'

# Encapsulate the plain and HTML versions of the message body in an
# 'alternative' part, so message agents can decide which they want to display.
msgAlternative = MIMEMultipart('alternative')

with open('*********.txt', 'r') as plainTXT:
    plain = plainTXT.read()
plainTXT.close()
msgAlternative.attach(MIMEText(plain))

with open('*********.html', 'r') as plainHTML:
    html = plainHTML.read()
plainHTML.close()
msgAlternative.attach(MIMEText(html))

msg.attach(msgAlternative)

# Image
for f in files or []:
    with open(f, "rb") as fp:
        part = MIMEImage(
            fp.read(),
            Name=basename(f)
        )
    # closing file
    part['Content-Disposition'] = 'attachment; filename="%s"' % basename(f)
    msg.attach(part)


# create server
server = smtplib.SMTP(server)
server.starttls()

# Login Credentials for sending the mail
server.login(login, password)

# send the message via the server.
server.sendmail(msg['From'], msg['To'], msg.as_string())

server.quit()

print("successfully sent email to %s:" % (msg['To']));

1 Ответ

0 голосов
/ 02 ноября 2018

Мне просто нужно было использовать MIMEText(html, 'html') для прикрепления части моего HTML. Рабочий код:

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.utils import formatdate
from os.path import basename
import smtplib

login = "YourLogin"
password = "YourPassword"
server = "SMTP-Server:Port"
files = ['files']

# Create the root message and fill in the from, to, and subject headers
msg = MIMEMultipart('related')
msg['From'] = "FromEmail"
msg['To'] = "ToEmail"
msg['Date'] = formatdate(localtime=True)
msg['Subject'] = "EmailSubject"
msg['Reply-To'] = "EmailReply"
msg.preamble = 'This is a multi-part message in MIME format.'

# Encapsulate the plain and HTML versions of the message body in an
# 'alternative' part, so message agents can decide which they want to display.
msgAlternative = MIMEMultipart('alternative')

with open('YourPlaintext.txt', 'r') as plainTXT:
    plain = plainTXT.read()
plainTXT.close()
msgAlternative.attach(MIMEText(plain, 'plain'))

with open('YourHTML.html', 'r') as plainHTML:
    html = plainHTML.read()
plainHTML.close()
msgAlternative.attach(MIMEText(html, 'html'))

msg.attach(msgAlternative)

# Image
for f in files or []:
    with open(f, "rb") as fp:
        part = MIMEImage(
            fp.read(),
            Name=basename(f)
        )
    # closing file
    part['Content-Disposition'] = 'attachment; filename="%s"' % basename(f)
    msg.attach(part)


# create server
server = smtplib.SMTP(server)
server.starttls()

# Login Credentials for sending the mail
server.login(login, password)

# send the message via the server.
server.sendmail(msg['From'], msg['To'], msg.as_string())

server.quit()

print("successfully sent email to %s:" % (msg['To']));

Благодаря @ tripleee

...