Add Subject header to server.sendmail() in Python

偶尔善良 提交于 2020-06-28 11:00:05

问题


I'm writing a python script to send emails from the terminal. In the mail which I currently send, it is without a subject. How do we add a subject to this email?

My current code:

    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()

回答1:


You need to put the subject in the header of the message.

Example -

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()



回答2:


You can simply use 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()

Hope this works!!!




回答3:


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")



回答4:


Indeed, the subject you missed. Those things can easily be avoided by using some API (such as yagmail) rather than the headers style.

I believe yagmail (disclaimer: I'm the maintainer) can be of great help to you, since it provides an easy API.

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

That's only three lines indeed.

Install with pip install yagmail or pip3 install yagmail for Python 3.

More info at github.



来源:https://stackoverflow.com/questions/31132108/add-subject-header-to-server-sendmail-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!