簡體   English   中英

用smtplib發送和接收的python電子郵件沒有內容

[英]python email sent and received with smtplib has no content

我正在使用帶有python的raspberrypi發送電子郵件。 我成功發送並收到了郵件,但內容丟失了。

這是我的代碼

import smtplib

smtpUser = 'myemail@gmail.com'
smtpPass = 'mypassword'

toAdd = 'target@gmail.com'
fromAdd = smtpUser

subject = 'Python Test'
header = 'To: ' + toAdd + '\n' + 'From: ' + fromAdd + '\n' + 'Subject: ' +             subject
body = 'From within a Python script'

msg = header + '\n' + body

print header + '\n' + body

s = smtplib.SMTP('smtp.gmail.com',587)

s.ehlo()
s.starttls()
s.ehlo()

s.login(smtpUser,smtpPass)
s.sendmail(fromAdd, toAdd, msg)

s.quit()

感謝您的關注!

我寫了一個圍繞在python中發送電子郵件的包裝器; 它使發送電子郵件變得非常簡單: https//github.com/krystofl/krystof-utils/blob/master/python/krystof_email_wrapper.py

像這樣使用它:

emailer = Krystof_email_wrapper()

email_body = 'Hello, <br /><br />' \
             'This is the body of the email.'

emailer.create_email('sender@example.com', 'Sender Name',
                     ['recipient@example.com'],
                     email_body,
                     'Email subject!',
                     attachments = ['filename.txt'])

cred = { 'email': 'sender@example.com', 'password': 'VERYSECURE' }

emailer.send_email(login_dict = cred, force_send = True)

您還可以查看源代碼以查找其工作原理。 相關位:

import email
import smtplib   # sending of the emails
from email.mime.multipart   import MIMEMultipart
from email.mime.text        import MIMEText

self.msg = MIMEMultipart()

self.msg.preamble   = "This is a multi-part message in MIME format."

# set the sender
author = email.utils.formataddr((from_name, from_email))
self.msg['From'] = author

# set recipients (from list of email address strings)
self.msg['To' ] = ', '.join(to_emails)
self.msg['Cc' ] = ', '.join(cc_emails)
self.msg['Bcc'] = ', '.join(bcc_emails)

# set the subject
self.msg['Subject'] = subject

# set the body
msg_text = MIMEText(body.encode('utf-8'), 'html', _charset='utf-8')
self.msg.attach(msg_text)

# send the email
session = smtplib.SMTP('smtp.gmail.com', 587)
session.ehlo()
session.starttls()
session.login(login_dict['email'], login_dict['password'])
session.send_message(self.msg)
session.quit()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM