试图在python中使用smtplib发送邮件。邮件正文与主题行

时间:2016-06-22 05:38:33

标签: python email email-attachments smtplib

这是一个奇怪的问题,自从过去2天以来一直困扰着我。我写了一个简单的发送邮件功能,它使用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)

2 个答案:

答案 0 :(得分:0)

  

我希望在主题中创建一个字符串应解析换行符并自动选择第二行作为正文

在文档中的任何地方都没有这样的保证。您已加入主题和正文并将其设置为主题,以便获得所需内容。

  

如果我不使用MIME消息而只使用字符串,则它们会被正确分开。但是,正常的字符串不允许图像附件。

我认为这意味着手动将消息构建为字符串。这意味着你正确构建了它,但这与Message object的工作原理无关。

要在多部分消息中包含正文,请按照examples

进行操作
from email.mime.text import MIMEText

...

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

答案 1 :(得分:0)

我创建了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")

如需介绍性阅读,请查看here