简体   繁体   English

如何以纯文本模式发送电子邮件换行符Python 3作为UTF8的MIME替代?

[英]How do I send email line feeds Python 3 in plain text mode as a MIME alternate with UTF8?

I have the following email code written in Python 3... I would like to send email as both HTML OR plain text depending on the receiving client. 我有以下用Python 3编写的电子邮件代码...我想根据接收的客户端以HTML或纯文本形式发送电子邮件。 However, both hotmail and gmail (I'm using the latter to send with) receive zero line feed/carriage return characters making the plain text appear on one line. 但是,hotmail和gmail(我正在使用后者发送)都收到零行换行/回车符,使纯文本显示在一行上。 My question is how do I get line feed/carriage returns in a plain text email on the receive side? 我的问题是如何在接收方以纯文本电子邮件的形式获取换行/回车? Thunderbird on Linux is my preferred client but I have noticed the same problem in Microsoft's webmail hotmail also. Linux上的Thunderbird是我的首选客户端,但我在Microsoft的Webmail 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

Here is the test code: 这是测试代码:

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)

Any suggestions would be most welcome as it seems everyone on the internet uses HTML email only. 任何建议都将受到欢迎,因为似乎互联网上的每个人都仅使用HTML电子邮件。 This is fine but I would like to be able to fall back to pure text for those of us who don't want to use HTML. 很好,但是对于那些不想使用HTML的人,我希望能够使用纯文本。

Thanks, 谢谢,

I can really recommend you using yagmail (Full disclaimer: I'm the developer/maintainer). 我真的可以推荐您使用yagmail (完全免责声明:我是开发人员/维护人员)。

Among its main purposes is to make it really easy to send attachments, and to send HTML code. 其主要目的之一是使发送附件和发送HTML代码变得非常容易。

Default text/inline images etc is in fact wrapped in HTML (so by default emails get sent as HTML). 默认的文本/嵌入式图像等实际上是用HTML包裹的(因此默认情况下,电子邮件将以HTML格式发送)。

File names get smart guessed on content and added as well. 文件名可以根据内容进行巧妙猜测,并且也可以添加。

Just stuff it all into contents, and yagmail will do the magic. 只需将所有内容填充到内容中, yagmail就能发挥作用。

However, and this is apparently important to you, it already sets up "alternative" mimeparts as well. 但是,这对您来说显然很重要,它也已经设置了“替代” mimepart。 No one has asked for it, so it could really use your help to mention bugs on the github tracker, if you find any. 没有人要求它,因此,如果您发现它,它可以真正使用您的帮助来提及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)

You can also set it up to be passwordless, then you can login without having username/password in script, ie 您还可以将其设置为无密码,然后可以在脚本中没有用户名/密码的情况下登录,即

yag = yagmail.SMTP()

Hope to have helped! 希望能有所帮助!

Most questions can be answered by reading the readme on github: https://github.com/kootenpv/yagmail 可以通过阅读github上的自述文件来回答大多数问题: https : //github.com/kootenpv/yagmail

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Python - 如何在 Heroku 上使用 JSON 解决 UTF8 问题? - Python - How do i solve UTF8 issues with JSON on Heroku? 如何使用 Python 的“MIME 处理包”发送电子邮件? - How do I send an email using Python's "MIME handling package"? 如何使用 Python 逐行匹配两个纯文本文件 - How do I match two plain text files line by line using Python 如何在命令行上处理 utf8(使用 Perl 或 Python)? - How to handle utf8 on the command line (using Perl or Python)? python和litesql:Unicode,utf8,如何正确执行? - python & litesql: unicode, utf8, how to do it properly? 如何使用python发送电子邮件? - how do i send an email in python? 如何使用Python 3.2电子邮件模块发送带有quoted-printable的utf-8编码的unicode消息? - How do I use Python 3.2 email module to send unicode messages encoded in utf-8 with quoted-printable? 如何将 python 中的字符串编码为 utf8 - How can I encode a string in python into utf8 在 python 中使用 MIME 发送 email 时如何向 Thunderbird 发送附件? - How to send Attachments to Thunderbird when sending email using MIME in python? 如何通过Celery发送HTML电子邮件? 它一直以文本/普通方式发送 - How can I send HTML email via Celery? It keeps sending in text/plain
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM