Send python email using SMTP with a subject - python

I am trying to send an email in Python using SMTP, with a From address, To address, BCC address, subject, and message. I have the email sending, and it even sends to the BCC as it should, the only issue is that the message of the email says:
To: example#gmail.com
Subject: Subject goes here
this is the email that I’m sending
when I only want the message itself to show where the message belongs, and the subject of the email isn't set, so there's a blank subject. Here is how I have it set up:
def sendEmail(fromAddress, toAddress, bccAddress, appName, message):
subject = "Subject goes here"
BODY = string.join((
"From: %s\r\n" % fromAddress,
"To: %s\r\n" % toAddress,
"Subject: %s\r\n" % subject,
"\r\n",
message
), "\r\n")
#im using arbitrary values here, when I run it I use actual login info
username = 'example#gmail.com'
password = 'password'
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.login(username,password)
toList = []
bccList = []
toList.append(toAddress)
bccList.append(bccAddress)
server.sendmail(fromAddress, toList + bccList, BODY)
server.quit()

Use the email package (docs).
from email.mime.text import MIMEText
def send_mail(to, from_addr, subject, text):
msg = MIMEText(text)
msg['Subject'] = subject
msg['From'] = from_addr
msg['To'] = to
s = smtplib.SMTP_SSL("smtp.gmail.com")
s.login(smtp_user, smtp_pass)
# for Python 3
s.send_message(msg)
# OR
# for Python 2 (or 3, will still work)
s.sendmail(from_addr, [to], msg.as_string())
s.quit()

Related

Sending email incl. Subject field ,using Python SMTP

I used server.sendmail(fromaddr, toaddrs, msg) to send automated emails using python.
How can I add an email subject to the mail?
I tried to look in SMTP documentation and didn't find any documentation for that.
From How to send an email with Gmail as provider using Python? :
def send_email(user, pwd, recipient, subject, body):
import smtplib
gmail_user = user
gmail_pwd = pwd
FROM = user
TO = recipient if type(recipient) is list else [recipient]
SUBJECT = subject
TEXT = body
# Prepare actual message
message = """From: %s\nTo: %s\nSubject: %s\n\n%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)
try:
server = smtplib.SMTP("smtp.gmail.com", 587)
server.ehlo()
server.starttls()
server.login(gmail_user, gmail_pwd)
server.sendmail(FROM, TO, message)
server.close()
print 'successfully sent the mail'
except:
print "failed to send mail"

Gmail SMTP graceful login

I'm using Gmail SMTP to send emails in Python, however sometimes the application may stay idle for an extended period of time.
How do I make sure that the session hasn't expired? Here's my code:
def send_email(user, pwd, recipient, subject, body):
import smtplib
gmail_user = user
gmail_pwd = pwd
FROM = user
TO = recipient if type(recipient) is list else [recipient]
SUBJECT = subject
TEXT = body
# Prepare actual message
message = """\From: %s\nTo: %s\nSubject: %s\n\n%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)
try:
server = smtplib.SMTP("smtp.gmail.com", 587)
server.ehlo()
server.starttls()
server.login(gmail_user, gmail_pwd)
server.sendmail(FROM, TO, message)
server.close()
print 'successfully sent the mail'
except:
print "failed to send mail"
Can I always reuse the server session, or can it expire after let's say 5 hours?

Python smtplib - No recipient after sending mail

I recently wrote a script that sent me an email if a website I wanted to monitor had changed using smtplib. The program works, and I get the email but when I look at the sent email (as I am sending myself the email from the same account), it says that there is no recipient or 'To:' address, only a Bcc with the address I want the email to be sent to. Is this a feature of smtplib -- that it doesn't actually add a 'To:' address, only Bcc addresses? code is as follows:
if (old_source != new_source):
# now we create a mesasge to send via email
fromAddr = "example#gmail.com"
toAddr = "example#gmail.com"
msg = ""
# smtp login
username = "example#gmail.com"
pswd = "password"
# create server object and login to the gmail smtp
server = smtplib.SMTP_SSL("smtp.gmail.com", 465)
server.login(username, pswd)
server.sendmail(fromAddr, toAddr, msg)
server.quit()
Updating your code as follows will do the trick:
if (old_source != new_source):
# now we create a mesasge to send via email
fromAddr = "example#gmail.com"
toAddr = "example#gmail.com"
msg = ""
# smtp login
username = "example#gmail.com"
pswd = "password"
# create server object and login to the gmail smtp
server = smtplib.SMTP_SSL("smtp.gmail.com", 465)
header = 'To:' + toAddr + '\n' + 'From: ' + fromAddr + '\n' + 'Subject:testing \n'
msg = header + msg
server.login(username, pswd)
server.sendmail(fromAddr, toAddr, msg)
server.quit()
Try manually adding any headers to your message, separated from the body by a blank line e.g.:
...
msg="""From: sender#domain.org
To: recipient#otherdomain.org
Subject: Test mail
Mail body, ..."""
...
Try this, seems to work for me.
#!/usr/bin/python
#from smtplib import SMTP # Standard connection
from smtplib import SMTP_SSL as SMTP #SSL connection
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
sender = 'example#gmail.com'
receivers = ['example#gmail.com']
msg = MIMEMultipart()
msg['From'] = 'example#gmail.com'
msg['To'] = 'example#gmail.com'
msg['Subject'] = 'simple email via python test 1'
message = 'This is the body of the email line 1\nLine 2\nEnd'
msg.attach(MIMEText(message))
ServerConnect = False
try:
smtp_server = SMTP('smtp.gmail.com','465')
smtp_server.login('######gmail.com', '############')
ServerConnect = True
except SMTPHeloError as e:
print "Server did not reply"
except SMTPAuthenticationError as e:
print "Incorrect username/password combination"
except SMTPException as e:
print "Authentication failed"
if ServerConnect == True:
try:
smtp_server.sendmail(sender, receivers, msg.as_string())
print "Successfully sent email"
except SMTPException as e:
print "Error: unable to send email", e
finally:
smtp_server.close()
Just throwing it out there: please try yagmail. Disclaimer: I'm the maintainer, but I feel like it can help everyone out!
It really provides a lot of defaults: I'm quite sure you'll be able to send an email directly with:
import yagmail
yag = yagmail.SMTP(username, password)
yag.send(to_addrs, contents = msg)
Which will also set the headers :)
You'll have to install yagmail first with either:
pip install yagmail # python 2
pip3 install yagmail # python 3
Once you will want to also embed html/images or add attachments, you'll really love the package!
It will also make it a lot safer by preventing you from having to have your password in the code.

Sending email using smtplib doesn't work anymore

So yesterday I had this bit of code written out and it worked perfectly fine, but today it's not sending e-mails anymore. Can someone explain why?
import smtplib
SERVER = 'owa.server.com'
FROM = 'noreply#server.com'
TO = ['person#gmail.com', '1112223344#vtext.com']
name = 'Mr. Man'
SUBJECT = 'Recent Information for: %s' % (name)
TEXT = "Dear " +name+ ",\n\nHello.\n\nSincerely,\nOur Guys Here"
message = """From: %s\r\nTo: %s\r\nSubject: %s\r\n\
%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)
server = smtplib.SMTP(SERVER, 587)
server.ehlo()
server.starttls()
server.ehlo
server.login('noreply#server.com', 'password')
server.sendmail(FROM, TO, message)
server.quit()
This code is a working snippet. I wasn't getting the e-mails in my personal gmail account because gmail was sending it to the spam folder. I checked to see if it works at my office account, and it did just fine.
import smtplib
# Specifying the from and to addresses
fromaddr = 'fromuser#gmail.com'
toaddrs = 'to#gmail.com'
# Writing the message (this message will appear in the email)
msg = 'Enter you message here'
# Gmail Login
username = 'username'
password = 'password'
# Sending the mail
server = smtplib.SMTP('smtp.gmail.com:587')
server.starttls()
server.login(username,password)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()
Above standard smtp send works with gmail,
thus it must be your server(whatever you're using) configuration that is at fault.

Python: "subject" not shown when sending email using smtplib module

I am successfully able to send email using the smtplib module. But when the emial is sent, it does not include the subject in the email sent.
import smtplib
SERVER = <localhost>
FROM = <from-address>
TO = [<to-addres>]
SUBJECT = "Hello!"
message = "Test"
TEXT = "This message was sent with Python's smtplib."
server = smtplib.SMTP(SERVER)
server.sendmail(FROM, TO, message)
server.quit()
How should I write "server.sendmail" to include the SUBJECT as well in the email sent.
If I use, server.sendmail(FROM, TO, message, SUBJECT), it gives error about "smtplib.SMTPSenderRefused"
Attach it as a header:
message = 'Subject: {}\n\n{}'.format(SUBJECT, TEXT)
and then:
server = smtplib.SMTP(SERVER)
server.sendmail(FROM, TO, message)
server.quit()
Also consider using standard Python module email - it will help you a lot while composing emails. Using it would look like this:
from email.message import EmailMessage
msg = EmailMessage()
msg['Subject'] = SUBJECT
msg['From'] = FROM
msg['To'] = TO
msg.set_content(TEXT)
server.send_message(msg)
This will work with Gmail and Python 3.6+ using the new "EmailMessage" object:
import smtplib
from email.message import EmailMessage
msg = EmailMessage()
msg.set_content('This is my message')
msg['Subject'] = 'Subject'
msg['From'] = "me#gmail.com"
msg['To'] = "you#gmail.com"
# Send the message via our own SMTP server.
server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
server.login("me#gmail.com", "password")
server.send_message(msg)
server.quit()
try this:
import smtplib
from email.mime.multipart import MIMEMultipart
msg = MIMEMultipart()
msg['From'] = 'sender_address'
msg['To'] = 'reciver_address'
msg['Subject'] = 'your_subject'
server = smtplib.SMTP('localhost')
server.sendmail('from_addr','to_addr',msg.as_string())
You should probably modify your code to something like this:
from smtplib import SMTP as smtp
from email.mime.text import MIMEText as text
s = smtp(server)
s.login(<mail-user>, <mail-pass>)
m = text(message)
m['Subject'] = 'Hello!'
m['From'] = <from-address>
m['To'] = <to-address>
s.sendmail(<from-address>, <to-address>, m.as_string())
Obviously, the <> variables need to be actual string values, or valid variables, I just filled them in as place holders. This works for me when sending messages with subjects.
See the note at the bottom of smtplib's documentation:
In general, you will want to use the email package’s features to construct an email message, which you can then convert to a string and send via sendmail(); see email: Examples.
Here's the link to the examples section of email's documentation, which indeed shows the creation of a message with a subject line. https://docs.python.org/3/library/email.examples.html
It appears that smtplib doesn't support subject addition directly and expects the msg to already be formatted with a subject, etc. That's where the email module comes in.
import smtplib
# creates SMTP session
List item
s = smtplib.SMTP('smtp.gmail.com', 587)
# start TLS for security
s.starttls()
# Authentication
s.login("login mail ID", "password")
# message to be sent
SUBJECT = "Subject"
TEXT = "Message body"
message = 'Subject: {}\n\n{}'.format(SUBJECT, TEXT)
# sending the mail
s.sendmail("from", "to", message)
# terminating the session
s.quit()
I think you have to include it in the message:
import smtplib
message = """From: From Person <from#fromdomain.com>
To: To Person <to#todomain.com>
MIME-Version: 1.0
Content-type: text/html
Subject: SMTP HTML e-mail test
This is an e-mail message to be sent in HTML format
<b>This is HTML message.</b>
<h1>This is headline.</h1>
"""
try:
smtpObj = smtplib.SMTP('localhost')
smtpObj.sendmail(sender, receivers, message)
print "Successfully sent email"
except SMTPException:
print "Error: unable to send email"
code from: http://www.tutorialspoint.com/python/python_sending_email.htm
In case of wrapping it in a function, this should work as a template.
def send_email(login, password, destinations, subject, message):
server = smtplib.SMTP_SSL("smtp.gmail.com", 465)
server.login(login, password)
message = 'Subject: {}\n\n{}'.format(subject, message)
for destination in destinations:
print("Sending email to:", destination)
server.sendmail(login, destinations, message)
server.quit()
try this out :
from = "myemail#site.com"
to= "someemail#site.com"
subject = "Hello there!"
body = "Have a good day."
message = "Subject:" + subject + "\n" + body
server.sendmail(from, , message)
server.quit()

Categories