2

Python 3 で書かれた次の電子メール コードがあります...受信クライアントに応じて、HTML またはプレーン テキストの両方で電子メールを送信したいと考えています。ただし、hotmail と gmail (私は後者を使用して送信しています) の両方がゼロの改行/キャリッジ リターン文字を受け取り、プレーン テキストが 1 行に表示されます。私の質問は、受信側のプレーン テキスト メールでライン フィード/キャリッジ リターンを取得するにはどうすればよいですか? Linux 上の Thunderbird は私の好みのクライアントですが、Microsoft の Web メール hotmail にも同じ問題があることに気付きました。

#!/usr/bin/env python3
# encoding: utf-8
"""
python_3_email_with_attachment.py
Created by Robert Dempsey on 12/6/14; edited by Oliver Ernster.
Copyright (c) 2014 Robert Dempsey. Use at your own peril.

This script works with Python 3.x
"""

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

COMMASPACE = ', '

def send_email(user, pwd, recipient, subject, bodyhtml, bodytext):
    sender = user
    gmail_password = pwd
    recipients = recipient if type(recipient) is list else [recipient]

    # Create the enclosing (outer) message
    outer = MIMEMultipart('alternative')
    outer['Subject'] = subject
    outer['To'] = COMMASPACE.join(recipients)
    outer['From'] = sender
    outer.preamble = 'You will not see this in a MIME-aware mail reader.\n'

    # List of attachments
    attachments = []

    # Add the attachments to the message
    for file in attachments:
        try:
            with open(file, 'rb') as fp:
                msg = MIMEBase('application', "octet-stream")
                msg.set_payload(fp.read())
            encoders.encode_base64(msg)
            msg.add_header('Content-Disposition', 'attachment', filename=os.path.basename(file))
            outer.attach(msg)
        except:
            print("Unable to open one of the attachments. Error: ", sys.exc_info()[0])
            raise

    part1 = MIMEText(bodytext, 'plain', 'utf-8')
    part2 = MIMEText(bodyhtml, 'html', 'utf-8')

    outer.attach(part1)
    outer.attach(part2)

    composed = outer.as_string()

    # Send the email
    try:
        with smtplib.SMTP('smtp.gmail.com', 587) as s:
            s.ehlo()
            s.starttls()
            s.ehlo()
            s.login(sender, gmail_password)
            s.sendmail(sender, recipients, composed)
            s.close()
        print("Email sent!")
    except:
        print("Unable to send the email. Error: ", sys.exc_info()[0])
        raise

テストコードは次のとおりです。

def test_example():

some_param = 'test'
another_param = '123456'
yet_another_param = '12345'

complete_html = pre_written_safe_and_working_html

email_text = "Please see :" + '\r\n' \
                + "stuff: " + '\r\n' + some_param + '\r\n' \
                + "more stuff: " + '\r\n' + another_param + '\r\n' \
                + "stuff again: " + '\r\n' + yet_another_param, + '\r\n'

recipients = ['targetemail@gmail.com']

send_email('myaddress@gmail.com', \
           'password', \
           recipients, \
           'Title', \
           email_text, \
           complete_html)

インターネット上の誰もが HTML メールのみを使用しているように見えるので、どんな提案も大歓迎です。これは問題ありませんが、HTML を使用したくない私たちのために純粋なテキストにフォールバックできるようにしたいと考えています。

ありがとう、

4

1 に答える 1

1

使用することを本当にお勧めしますyagmail(完全な免責事項: 私は開発者/メンテナーです)。

その主な目的の 1 つは、添付ファイルの送信と HTML コードの送信を非常に簡単にすることです。

デフォルトのテキスト/インライン画像などは、実際には HTML でラップされています (デフォルトでは、メールは HTML として送信されます)。

ファイル名はコンテンツに基づいてスマートに推測され、同様に追加されます。

すべてをコンテンツに詰め込むだけでyagmail、魔法のようになります。

ただし、これは明らかに重要であり、「代替」の mimepart も既に設定されています。誰もそれを求めていないので、もし見つけたら、github トラッカーのバグに言及するために本当にあなたの助けを借りることができます.

import yagmail
yag = yagmail.SMTP('myaddress@gmail.com', 'password')

contents = ['/local/file.png', 'some text',
            '<b><a href="https://github.com/kootenpv/yagmail">a link</a></b>']

yag.send(to='targetemail@gmail.com', subject='Title', contents = contents)

パスワードレスに設定することもできます。そうすれば、スクリプトにユーザー名/パスワードを入力せずにログインできます。つまり、

yag = yagmail.SMTP()

お役に立てば幸いです!

ほとんどの質問は、github の readme を読むことで解決できます: https://github.com/kootenpv/yagmail

于 2015-10-03T15:28:10.080 に答える