在Python中将subject标题添加到server.sendmail()

时间:2015-06-30 07:27:49

标签: python email smtp

我正在写一个python脚本来从终端发送电子邮件。在我目前发送的邮件中,它没有主题。我们如何在此电子邮件中添加主题?

我目前的代码:

    import smtplib

    msg = """From: hello@hello.com
    To: hi@hi.com\n
    Here's my message!\nIt is lovely!
    """

    server = smtplib.SMTP_SSL('smtp.example.com', port=465)
    server.set_debuglevel(1)
    server.ehlo
    server.login('examplelogin', 'examplepassword')
    server.sendmail('me@me.com', ['anyone@anyone.com '], msg)
    server.quit()

4 个答案:

答案 0 :(得分:2)

您需要将subject放在邮件的标题中。

示例 -

import smtplib

msg = """From: hello@hello.com
To: hi@hi.com\n
Subject: <Subject goes here>\n
Here's my message!\nIt is lovely!
"""

server = smtplib.SMTP_SSL('smtp.example.com', port=465)
server.set_debuglevel(1)
server.ehlo
server.login('examplelogin', 'examplepassword')
server.sendmail('me@me.com', ['anyone@anyone.com '], msg)
server.quit()

答案 1 :(得分:1)

您可以简单地使用MIMEMultipart()

from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase

msg = MIMEMultipart()
msg['From'] = 'EMAIL_USER'
msg['To'] = 'EMAIL_TO_SEND'
msg['Subject'] = 'SUBJECT'

body = 'YOUR TEXT'
msg.attach(MIMEText(body,'plain'))

text = msg.as_string()
server = smtplib.SMTP('smtp.gmail.com',587)
server.starttls()
server.login('email','password')
server.sendmail(email_user,email_send,text)
server.quit()

希望这行得通!!!

答案 2 :(得分:0)

确实,你错过了这个主题。通过使用某些API(例如yagmail)而不是标题样式,可以轻松避免这些事情。

我相信yagmail(免责声明:我是维护者)对您有很大的帮助,因为它提供了一个简单的API。

import yagmail
yag = yagmail.SMTP('hello@gmail.com', 'yourpassword')
yag.send(to = 'hi@hi.com', subject ='Your subject', contents = 'Some message text')

这确实只有三行。

使用{3}}或pip install yagmail安装Python 3。

github的更多信息。

答案 3 :(得分:0)

import smtp

def send_email(SENDER_EMAIL,PASSWORD,RECEIVER_MAIL,SUBJECT,MESSAGE):
    try:
        server = smtplib.SMTP("smtp.gmail.com",587)
#specify server and port as per your requirement
        server.starttls()
        server.login(SENDER_EMAIL,PASSWORD)
        message = """From: %s\nTo: %s\nSubject: %s\n\n%s""" % (SENDER_EMAIL, ", ".join(TO), SUBJECT, MESSAGE)
        server.sendmail(SENDER_EMAIL,TO,message)
        server.quit()
        print 'successfully sent the mail'
    except:
        print "failed to send mail"
send_email("sender@gmail.com","Password","receiver@gmail.com","SUBJECT","MESSAGE")