Python smtplib:如何发送看起来像从电子邮件帐户发送的电子邮件的消息

Python smtplib: How to send messages that look like emails sent from email account

我正在尝试使用 Python 给自己发送短信。为此,我创建了一个 gmail 帐户,打开了 less secure apps 和 运行 以下代码:

import smtplib
from email.mime.text import MIMEText

# Establish a secure session with gmail's outgoing SMTP server using your gmail account
server = smtplib.SMTP('smtp.gmail.com', 587)
server.set_debuglevel(1)
server.ehlo()
server.starttls()
server.login('me@gmail.com', 'pw!' )

msg = '\r\n'.join([
  'From: me@gmail.com',
  'To: 5551234567@tmomail.net',
  'Subject: Cats',
  '',
  'on wheels'
])

# sendmail(from, to, msg)
server.sendmail('me@gmail.com', '5551234567@tmomail.net', msg)

这确实向我的 phone 发送了一条短信,但消息显示如下:

me@gmail.com / Cats / on wheels

此外,"from" 座席在我的短信列表中显示为一对 运行dom 带连字符的数字,例如“970-2”或“910-2”。

但是,当我从 gmail 本身向我的 phone 号码发送消息时,它在我的短信列表中显示为来自 "me@gmail.com" 并显示如下:

<b>Subject is here</b>
Body of email is here

有没有办法让我更改上面的 msg 对象,使从 Python 发送的邮件像从 Gmail 本身发送的邮件一样显示?

其他人就此问题提供的任何建议都将非常有帮助!

为了解决这个问题,我从 Gmail 发送了一封电子邮件,然后单击已发送邮件旁边的三个点,然后单击 "Show Original",它显示了 Gmail 服务器传送的完整数据包。然后我将这些字段添加到我的消息中:

import smtplib
import email.mime.multipart

# Establish a secure session with gmail's outgoing SMTP server using your gmail account
server = smtplib.SMTP('smtp.gmail.com', 587)
server.set_debuglevel(1)
server.ehlo()
server.starttls()
server.login('me@gmail.com', pw)

msg = '\r\n'.join([
  'MIME-Version: 1.0',
  'Date: Fri, 22 Feb 2019 11:29:27 -0500',
  'Message-ID: <CAKyky413ikdYD4-Oq_H_FPF-g__weSFehQNLVuspotupWhJaLA@mail.gmail.com>',
  'Subject: wow on what',
  'From: Ludwig Wittgenstein <me@gmail.com>',
  'To: 5551234567@tmomail.net',
  'Content-Type: multipart/alternative; boundary="0000000000003c664305827e1862"',
  '',
  '--0000000000003c664305827e1862',
  'Content-Type: text/plain; charset="UTF-8"',
  '',
  'weeeee',
  '',
  '--0000000000003c664305827e1862',
  'Content-Type: text/html; charset="UTF-8"',
  'Content-Transfer-Encoding: quoted-printable',
  '',
  '<div dir=3D"ltr">here=C2=A0</div>',
  ''
  '--0000000000003c664305827e1862--'
])

# sendmail(from, to, msg)
server.sendmail('me@gmail.com', '5551234567@tmomail.net', msg)