簡體   English   中英

使用Python和Gmail SMTP服務器發送電子郵件不適用於附件

[英]Sending email with Python and Gmail SMTP server doesn't work with attachment

我正在嘗試發送附有PDF的電子郵件。 我定義了下一個函數:

def mail(to, subject, text, attach):
    gmail_user = "email@gmail.com"
    gmail_name = "name <email@gmail.com>"
    gmail_pwd = "password"

    msg = MIMEMultipart()

    msg['From'] = gmail_name
    msg['To'] = to
    msg['Subject'] = subject

    msg.attach(MIMEText(text))

    part = MIMEBase('application', 'octet-stream')
    part.set_payload(open(attach, 'rb').read())
    Encoders.encode_base64(part)
    part.add_header('Content-Disposition',
           'attachment; filename="%s"' % os.path.basename(attach))
    msg.attach(part)

    mailServer = smtplib.SMTP("smtp.gmail.com", 587)

    mailServer.ehlo()
    mailServer.starttls()
    mailServer.ehlo()
    mailServer.login(gmail_user, gmail_pwd)
    mailServer.sendmail(gmail_name, to, msg.as_string())
    mailServer.close()

問題是控制台顯示以下錯誤

smtplib.SMTPServerDisconnected: Server not connected

但是,如果我只是將“ msg.as_string”替換為“ Whatever string”,則效果很好。 因此,我認為在嘗試附加PDF文件時會發生此問題。

請問你能幫幫我嗎 ?

謝謝

您還可以使用專門用於編寫HTML電子郵件,內聯顯示圖片並輕松附加文件的軟件包!

我指的是yagmail ,我是開發人員/維護人員。

import yagmail
yag = yagmail.SMTP(gmail_name, gmail_pwd)
yag.send('xyz@gmail.com', 'Sample subject', contents = attach)

這就是全部(3行對69行)!

使用pip install yagmail獲取您的副本。

內容可以是一個列表,您還可以在其中添加文本,但是由於您沒有文本,因此只能將attach文件名作為內容,真棒嗎? 它讀取文件,神奇地確定編碼,並附加它:)

我相信您應該更改此: part = MIMEBase('application', 'pdf')
檢查如何使用Python out 發送帶有.csv附件的電子郵件,以了解如何猜測文件類型。
其他可能的問題:

  • 嘗試添加標頭,如下所示: attachment.add_header("Content-Disposition", "attachment", filename=fileToSend)
  • 您在這條線上使用什么編碼器? Encoders.encode_base64(part) 我認為您應該from email import encoders ,然后再使用encoders.encode_base64(part)

嘗試這個-

import smtplib
import mimetypes
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email.Utils import COMMASPACE, formatdate
from email import Encoders


filePath = "fileName.pdf"

From = 'abc@gmail.com'
To = 'xyz@gmail.com'

msg = MIMEMultipart()
msg['From'] = From
msg['To'] = To
msg['Date'] = formatdate(localtime=True)
msg['Subject'] = 'Sample subject'

msg.attach(MIMEText('Sample message'))

try:
    smtp = smtplib.SMTP('smtp.gmail.com:587')
    smtp.starttls()
    smtp.login('abc@gmail.com', '123456')
except:
    i = 1
else:
    i = 0

if i == 0:
    ctype, encoding = mimetypes.guess_type(filePath)
    if ctype is None or encoding is not None:
        # No guess could be made, or the file is encoded (compressed), so
        # use a generic bag-of-bits type.
        ctype = 'application/octet-stream'
    maintype, subtype = ctype.split('/', 1)
    if maintype == 'text':
        fp = open(filePath)
        # Note: we should handle calculating the charset
        part = MIMEText(fp.read(), _subtype=subtype)
        fp.close()
    elif maintype == 'image':
        fp = open(filePath, 'rb')
        part = MIMEImage(fp.read(), _subtype=subtype)
        fp.close()
    elif maintype == 'audio':
        fp = open(filePath, 'rb')
        part = MIMEAudio(fp.read(), _subtype=subtype)
        fp.close()
    else:
        fp = open(filePath, 'rb')
        part = MIMEBase(maintype, subtype)
        part.set_payload(fp.read())
        fp.close()
        # Encode the payload using Base64
        Encoders.encode_base64(part)
    part.add_header('Content-Disposition', 'attachment; filename="%s"' % filePath)
    msg.attach(part)
    try:
        smtp.sendmail(From, To, msg.as_string())
    except:
        print "Mail not sent"
    else:
        print "Mail sent"
    smtp.close()
else:
    print "Connection failed"

改編自: https : //docs.python.org/2/library/email-examples.html

暫無
暫無

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

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