发送电子邮件附件python

时间:2015-11-25 02:25:49

标签: python email indentation

  

我正在尝试通过python发送电子邮件,但我得到了       msg.addpayload(部分)上出现意外的unindent错误。我正进入(状态       当我复制+粘贴其他时,同一个msg.attach(部分)上的错误       人民代码也是如此。

def sendemail(logfile, password='somepassword'):
    # Initialize email sender/receiver/servers 
    email_subject = logfile 
    email_receiver = 'email@gmail.com' 
    email_sender = 'someemail@gmail.com'
    gmail_smtp = 'smtp.gmail.com'
    gmail_smtp_port = 587
    text_subtype = 'plain'
    filepath = os.path.abspath(logfile)

    # Create the message 
    msg = MIMEMultipart()
    msg['From'] = email_sender
    msg['To'] = email_receiver
    msg['Date'] = formatdate(localtime=True)
    msg['Subject'] = str(email_subject)

    part = MIMEBase('application','octet-stream')
    part.set_payload( open(logfile, 'rb').read() )
    Encoders.encode_base64(part)
    part.add_header('Content-Disposition','attachment',filename=filepath)
    # Attach file to message

    msg.add_payload(part)

    # try:
    server_gmail = smtplib.SMTP(gmail_smtp, gmail_smtp_port)
        # Identify self to gmail server 
    server_gmail.ehlo()
        # Put SMTP connection in TLS mode and call ehlo again 
    server_gmail.starttls() 
    #server_gmail.ehlo()
        # Login to service 
    server_gmail.login(email_sender,password)
        # Send email 
    server_gmail.sendmail(email_sender,email_receiver,msg.as_string())
        # Close connection 
    server_gmail.close() 
    print("mail sent")
    # except:
    #   print("failed to send mail")
sendemail('logtest.csv', 'somepassword')

1 个答案:

答案 0 :(得分:2)

您在缩进中混合制表符和空格。这让Python感到困惑。

enter image description here

只使用其中一种,而不是两种。空格是可取的。