簡體   English   中英

嘗試在python中使用smtplib發送郵件。 郵件正文與主題行一起出現

[英]Trying to send a mail using smtplib in python. Mail body comes alongwith subject line

自從過去兩天以來,這一直困擾着我。 我編寫了一個簡單的發送郵件功能,該功能使用smtplib發送帶有圖像作為附件的電子郵件。

問題在於主體部分被連接到主題行。 如果我不使用MIME消息而只是一個字符串,則它們會正確分開。 但是,然后普通字符串不允許圖像附件。

我在這里缺少任何圖書館嗎?

請輸入以下代碼:

# -*- coding: utf-8 -*-
"""
Created on Tue Jun 14 20:08:00 2016

@author: HOME
"""

import smtplib
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText 
import base64
import time
import datetime

print str(datetime.datetime.now())


def send_mail(pwd):

    password = base64.b64decode(pwd)

    # in the prod system, ask the mail exchange server and port

    server = smtplib.SMTP('smtp.gmail.com:587')
    server.ehlo()
    server.starttls()

    server.login('someemail@gmail.com', password)

    msg = MIMEMultipart()

    body = "\nThe message body is this one. Thanks \n\n"
    subject = "Your daily digest " + str(datetime.datetime.now())

    msg['From'] = "someemail@gmail.com"
    msg['To'] = "someemail@gmail.com"

    # I was hoping that creating a string in the subject should parse for newline and automatically pick the 2nd line onwards as body
    # If I send mail using the commented code (line 46 t0 line 52), the subject and body are different. But I am unable to attach images
    # but if i use the MIMEMultipart message , then i can attach images, but the body comes in the subject line 
    msg['Subject'] = "\r\n".join([subject,"",body])

    #msg.attach(MIMEText(body,'text'))
    msg.preamble = 'Daily Updates'
    """
    msg = "\r\n".join([
    "From: someemail@gmail.com",
    "To: someemail@gmail.com",
    "Subject: Daily digest " + str(datetime.datetime.now()),
    "",
    "Good Morning, How are you ? "
    ])

    """
    # Image attachment code
    fp = open("D://sample.png",'rb')
    img = MIMEImage(fp.read())
    msg.attach(img)

    print msg
    #try:
    server.sendmail('someemail@gmail.com','someemail@gmail.com',msg.as_string())
    print "Mail send successfully to someemail@gmail.com"
    server.close()
    #except:
    #   print "Mail not sent"

if __name__ == '__main__':
    pwd = base64.b64encode('howdy')
    send_mail(pwd)

我希望在主題中創建一個字符串應該解析換行符,然后自動選擇第二行作為正文

文檔中的任何地方均未提供此類保證。 您正在加入主題和主體並將它們設置為主題,這就是您所得到的。

如果我不使用MIME消息而只是一個字符串,則它們會正確分開。 但是,然后普通字符串不允許圖像附件。

我的意思是手動將消息構建為字符串。 這意味着您正確地構建了它,但是與Message對象的工作方式無關。

要將主體包含在多部分消息中,請遵循以下示例

from email.mime.text import MIMEText

...

msg.attach(MIMEText(body, 'plain'))

我創建了yagmail ,以便非常輕松地發送附件。

import yagmail
yag = yagmail.SMTP(username, password)
yag.send(to="myfriend@gmail.com", 
         subject="Daily digest " + str(datetime.datetime.now()), 
         contents="Good Morning, How are you ?", 
         attachments="D://sample.png")

如需入門閱讀,請在這里看看。

暫無
暫無

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

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