简体   繁体   English

使用Python和Gmail SMTP服务器发送电子邮件不适用于附件

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

I'm trying send email with a PDF attached. 我正在尝试发送附有PDF的电子邮件。 I have defined the next function: 我定义了下一个函数:

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()

The problem is that the console shows the following error 问题是控制台显示以下错误

smtplib.SMTPServerDisconnected: Server not connected

However, if I simply replace 'msg.as_string' with "Whatever string" it works fine. 但是,如果我只是将“ msg.as_string”替换为“ Whatever string”,则效果很好。 So I think that this issue happens when I try attach a PDF file. 因此,我认为在尝试附加PDF文件时会发生此问题。

Could you help me please ? 请问你能帮帮我吗 ?

Thanks 谢谢

You could also use a package specialised for writing HTML emails, showing pictures inline and easily attach files! 您还可以使用专门用于编写HTML电子邮件,内联显示图片并轻松附加文件的软件包!

The package I'm referring to is yagmail and I'm the developer/maintainer. 我指的是yagmail ,我是开发人员/维护人员。

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

That's all there is to it (3 lines vs 69 lines)!! 这就是全部(3行对69行)!

Use pip install yagmail to obtain your copy. 使用pip install yagmail获取您的副本。

Contents can be a list where you also add text, but since you don't have text, you can just only have the attach filename as contents, awesome no? 内容可以是一个列表,您还可以在其中添加文本,但是由于您没有文本,因此只能将attach文件名作为内容,真棒吗? It reads the file, magically determines the encoding, and attached it :) 它读取文件,神奇地确定编码,并附加它:)

I believe you should change this: part = MIMEBase('application', 'pdf') . 我相信您应该更改此: part = MIMEBase('application', 'pdf')
Check How do I send an email with a .csv attachment using Python out for how to try to guess the file type. 检查如何使用Python out 发送带有.csv附件的电子邮件,以了解如何猜测文件类型。
Other possible issues: 其他可能的问题:

  • try adding the header like this: attachment.add_header("Content-Disposition", "attachment", filename=fileToSend) 尝试添加标头,如下所示: attachment.add_header("Content-Disposition", "attachment", filename=fileToSend)
  • what Encoders are you using on this line? 您在这条线上使用什么编码器? Encoders.encode_base64(part) . Encoders.encode_base64(part) I think you should be using from email import encoders and then encoders.encode_base64(part) 我认为您应该from email import encoders ,然后再使用encoders.encode_base64(part)

Try this- 尝试这个-

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"

Adapted from: https://docs.python.org/2/library/email-examples.html 改编自: https : //docs.python.org/2/library/email-examples.html

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

相关问题 在电子邮件 BytesIO 中发送带有附件的消息不起作用 - 没有显示错误 - Python/Smtp/Email - Sending message with attachment in email BytesIO doesn't work - No errors shown - Python/Smtp/Email python smtp gmail身份验证错误(通过gmail smtp服务器发送电子邮件) - python smtp gmail authentication error (sending email through gmail smtp server) 使用 Gmail 和 SMTP 发送电子邮件时出错(Python 3) - Error Sending Email using Gmail with SMTP (Python 3) 我的Python尝试通过Gmail通过SMTP通过SMTP发送邮件有什么问题? SSL包装器似乎无效 - What's wrong with my Python attempt at sending mail via SMTP through Gmail? The SSL wrapper doesn't seem to work 使用电子邮件 python 库获取附件名称不起作用 - Using email python library to get attachment name doesn't work 通过Python和Google SMTP服务器发送电子邮件 - Sending email via Python and Google SMTP server 发送电子邮件附件python - Sending email attachment python 使用Python发送带有附件的电子邮件 - Sending email with attachment in Python Python:使用SMTP发送邮件(至Gmail),并且无法正确编码标头 - Python: sending mail with SMTP (to Gmail) and can't encode headers properly Python:发送电子邮件时,始终在子句中阻止:smtpserver = smtplib.SMTP(“smtp.gmail.com”,587) - Python: when sending email, always blocked in the clause: smtpserver = smtplib.SMTP(“smtp.gmail.com”,587)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM