13

重複の可能性:
Pythonで電子メールの添付ファイルを送信する方法

次のコードを編集して、添付ファイル付きのメールを送信したいと思います。添付ファイルはPDFファイルで、Linux環境では/home/myuser/sample.pdfの下にあります。以下で何を変更すればよいですか?

import smtplib  
fromaddr = 'myemail@gmail.com'  
toaddrs  = 'youremail@gmail.com'  
msg = 'Hello'  


# Credentials (if needed)  
username = 'myemail'  
password = 'yyyyyy'  

# The actual mail send  
server = smtplib.SMTP('smtp.gmail.com:587')  
server.starttls()  
server.login(username,password)  
server.sendmail(fromaddr, toaddrs, msg)  
server.quit()  
4

2 に答える 2

25

この場合、メール パッケージを使用してメッセージを作成します。

from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEImage import MIMEImage
msg = MIMEMultipart()
msg.attach(MIMEText(open("/home/myuser/sample.pdf").read()))

メッセージを送信します。

import smtplib
mailer = smtplib.SMTP()
mailer.connect()
mailer.sendmail(from_, to, msg.as_string())
mailer.close()

ここにいくつかの例があります - http://docs.python.org/library/email-examples.html

アップデート

上記のリンクを更新すると、404 https://docs.python.org/2/library/email-examples.htmlが生成されます。ありがとう@Tシャツマン


Update2: PDF を添付する最も簡単な方法

アタッチするにpdfは、pdf フラグを使用します。

def send_email_pdf_figs(path_to_pdf, subject, message, destination, password_path=None):
    ## credits: http://linuxcursor.com/python-programming/06-how-to-send-pdf-ppt-attachment-with-html-body-in-python-script
    from socket import gethostname
    #import email
    from email.mime.application import MIMEApplication
    from email.mime.multipart import MIMEMultipart
    from email.mime.text import MIMEText
    import smtplib
    import json

    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.starttls()
    with open(password_path) as f:
        config = json.load(f)
        server.login('me@gmail.com', config['password'])
        # Craft message (obj)
        msg = MIMEMultipart()

        message = f'{message}\nSend from Hostname: {gethostname()}'
        msg['Subject'] = subject
        msg['From'] = 'me@gmail.com'
        msg['To'] = destination
        # Insert the text to the msg going by e-mail
        msg.attach(MIMEText(message, "plain"))
        # Attach the pdf to the msg going by e-mail
        with open(path_to_pdf, "rb") as f:
            #attach = email.mime.application.MIMEApplication(f.read(),_subtype="pdf")
            attach = MIMEApplication(f.read(),_subtype="pdf")
        attach.add_header('Content-Disposition','attachment',filename=str(path_to_pdf))
        msg.attach(attach)
        # send msg
        server.send_message(msg)

インスピレーション/クレジット: http://linuxcursor.com/python-programming/06-how-to-send-pdf-ppt-attachment-with-html-body-in-python-script

于 2012-08-12T09:44:47.767 に答える
6

推奨される方法は、適切にフォーマットされたMIMEメッセージを作成するためにPythonの電子メールモジュールを使用することです。ドキュメントを参照してください

Python2の場合
https://docs.python.org/2/library/email-examples.html

Python3の場合
https://docs.python.org/3/library/email.examples.html

于 2012-08-12T09:44:13.820 に答える