在Python邮件功能中填充其他电子邮件字段,例如“主题”

时间:2018-11-29 08:59:21

标签: python smtp gmail smtplib

我已经测试了这段代码,它成功发送了电子邮件,如图所示,它倾向于将主题字段,抄送和密件抄送字段留空。

import smtplib

gmail_user = 'dummy@gmail.com'  
gmail_password = 'password'



sent_from = 'dummy@gmail.com'  
to = ['receiver@gmail.com']  
subject = 'OMG Super Important Message'  
body = "Hey, what's up?\n\n- You"

email_text = """\
From: %s  
To: %s  
Subject: %s

%s
""" % (sent_from, ", ".join(to), subject, body)

try:  
    server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
    print("establish connection successful")
    server.ehlo()
    print("identification successful")
    server.login(gmail_user, gmail_password)
    print("login successful")
    server.sendmail(sent_from, to, email_text)
    print("send mail successful")
    server.close()
    print('Email sent!')
except:  
    print('Something went wrong...')

有人知道我如何通过此脚本填写它们吗?

Screenshot of received mail

2 个答案:

答案 0 :(得分:1)

对于电子邮件主题-您提供给server.sendmail的输入arg有一种特定的格式应该可以使用。您可以尝试:

subject = 'This is the email subject'
text = 'This is the email body'
message = "Subject: {}\n\n{}".format(subject, text)
server.sendmail(sender, recipient, message)

答案 1 :(得分:0)

如果您尝试打开电子邮件的来源,您将看到类似以下的内容:

   Received: from ************.net ([***.**.2.17]) by
   *****.****.net ([**.***.224.162]) with mapi id **.03.****.***;
   Mon, 22 May 2017 09:14:59 +0200
   From: *FROMEMAIL* <******@***.com>
   To: *TOEMAIL* <********@***.com>
   CC: *CCEMAIL* <********@*****.com>
   Subject: E-mail - 150633**0686_****.pdf
   ...

这是电子邮件的标题,因此,如果您尝试这样的操作:

import smtplib

gmail_user = 'dummy@gmail.com'  
gmail_password = 'password'



sent_from = 'dummy@gmail.com'  
to = ['receiver@gmail.com']  
subject = 'OMG Super Important Message'  
body = "Hey, what's up?\n\n- You"
cc = "****@***.com"
bcc = "******@*****.com"
email_text = """\
From: %s  
To: %s
CC: %s
BCC: %s
Subject: %s

%s
""" % (sent_from, ", ".join(to), cc, bcc,subject, body)

try:  
    server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
    print("establish connection successful")
    server.ehlo()
    print("identification successful")
    server.login(gmail_user, gmail_password)
    print("login successful")
    server.sendmail(sent_from, to, email_text)
    print("send mail successful")
    server.close()
    print('Email sent!')
except:  
    print('Something went wrong...')

我认为它将起作用