Sending reports from my python script using gmail smtp - python

I'm trying to send email to myself with all reports collect each day from my scripts and below is the code I'm using to send the email.
# Import smtplib for the actual sending function
import smtplib
# Import the email modules we'll need
from email.mime.text import MIMEText
def send_email(message="", subject="EReport of Twitter Bot"):
msg = MIMEText(message)
# me == the sender's email address
# you == the recipient's email address
msg['Subject'] = subject
msg['From'] = 'r****#gmail.com'
msg['To'] = 'r****#gmail.com'
# Send the message via our own SMTP server, but don't include the
# envelope header.
try:
s = smtplib.SMTP('smtp.gmail.com',465)
s.ehlo()
s.starttls()
s.ehlo()
s.login('r****#gmail.com', 'mypassword')
s.sendmail('r****#gmail.com', 'r****#gmail.com', msg.as_string())
s.quit()
return True
except Exception as e:
print e
return False
if __name__ == "__main__":
if send_email(message="Hello Ravi!"):
print "Successfully sent the mail"
else:
print "Sorry"
However, I get Connection unexpectedly closed when using the port 465. And If I use port 587 I get the following
(534, '5.7.14 <https://accounts.google.com/ContinueSignIn?sarp=1&scc=1&plt=AKgnsbvkf\n5.7.14 g4kEFJrti_fMva0wSRWGl4KfuNsFhQumLhgzMCUlPCQn2dvYdPCDr03l9luBP2XTwcnf_N\n5.7.14 BNsPV2jZhLOPjFOSYtGM16Wb6A1BlmLvMP1_mMHoeo4plSVNGio8EDCx_RMW7HcJdYcpx9\n5.7.14 T5SHwceKzRdpUXHxdL2icc0KAMDtb1dDLDr389N_s-tnSkylcN0bwctBA0tKF2k0AC6OsX\n5.7.14 jIcP7iV3ArV6PEB2ZXPCOI2gRPg0> Please log in via your web browser and\n5.7.14 then try again.\n5.7.14 Learn more at\n5.7.14 https://support.google.com/mail/answer/78754 lq10sm97657764pab.36 - smtp')
Which basically means my server is not trust worthy, although reverse-dns on my server's ip returns valid rent-history.com
Does anyone know what I can do/try to fix this?

Port 465 is used for SSL, port 587 not.
You should use SMTP_SSL when you intend to use secure connection (port 465), and SMTP with port 587.
Also, I'd like to point out yagmail; I developed it.
You can just use:
import yagmail
yag = yagmail.SMTP('r****#gmail.com', 'pw') # or yagmail.SMTP_SSL for port 465
yag.send('r****#gmail.com', "EReport of Twitter Bot", message)
Furthermore, it makes it easy to:
write the script in a passwordless manner
adding files by filenames (and it will automatically attach it using the correct mimetype)
it automatically sends HTML emails and uses plain text fallback
Install using pip (works for both python 2 and 3):
pip install yagmail

You may need to log into whatever gmail account you are using and go to the less secure apps secion to enable access via a less secure app, such as your program. Obviously, this decreases the account's security, so I don't recommend you do this with a personal account.

Related

Using domain email with Yagmail

I'm working in a company that uses Gmail to send and receive emails from a domain email. To make it clearer, let's say it's firstname#company.com.
Right now my goal is to make a simple script that will send the emails using a list from csv file. The code works fine when I use my personal Gmail email, but the problem starts when I change it to my business account - it seems that the script is ignoring the initialization step because it's not #gmail.com.
Not sure if it's needed, but right now I will be happy to at least run the "yagmail 101" code like the one below. Just for reference, I tried the smtplib as well with same result. The two-factor authentication is on, a 16-char password for Windows mail application was created.
#importing the Yagmail library
import yagmail
try:
#initializing the server connection
yag = yagmail.SMTP(user='firstname#company.com', password='mypassword')
#sending the email
yag.send(to='recipient_username#gmail.com', subject='Testing Yagmail', contents='Hurray, it worked!')
print("Email sent successfully")
except:
print("Error, email was not sent")
#importing the Yagmail library
import yagmail
# connect to smtp server.
yag_smtp_connection = yagmail.SMTP( user="user#company.com", password="mypassword",
host='yourSMTPserver')
# email subject
subject = 'Hello'
contents = ['Hello this email send via YAGMAIL']
# send the email
yag_smtp_connection.send('to#gmail.com', subject, contents)
print("Email send!")

send email using SMTP SSL/Port 465

I need to send email using SMTP SSL/Port 465 with my bluehost email.I can't find working code in google i try more than 5 codes. So, please any have working code for sending email using SMTP SSL/port 465 ?
Jut to clarify the solution from dave here is how i got mine to work with my SSL server (i'm not using gmail but still same). Mine emails if a specific file is not there (for internal purposes, that is a bad thing)
import smtplib
import os.path
from email.mime.text import MIMEText
if (os.path.isfile("filename")):
print "file exists, all went well"
else:
print "file not exists, emailing"
msg = MIMEText("WARNING, FILE DOES NOT EXISTS, THAT MEANS UPDATES MAY DID NOT HAVE BEEN RUN")
msg['Subject'] = "WARNING WARNING ON FIRE FIRE FIRE!"
#put your host and port here
s = smtplib.SMTP_SSL('host:port')
s.login('email','serverpassword')
s.sendmail('from','to', msg.as_string())
s.quit()
print "done"
For SSL port 465, you need to use SMTP_SSL, rather than just SMTP.
See here for more info.
https://docs.python.org/2/library/smtplib.html
You should never post a question like this. Please let us know what you have done, any tries? Any written code etc.
Anyways I hope this helps
import smtplib
fromaddr = 'uremail#gmail.com'
toaddrs = 'toaddress#ymail.com'
msg = "I was bored!"
# Credentials
password = 'password'
# The actual mail send
server = smtplib.SMTP('smtp.gmail.com:587')
server.starttls()
server.login(fromaddr,password)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()
print "done"

Send anonymous mail from local machine

I was using Python for sending an email using an external SMTP server. In the code below, I tried using smtp.gmail.com to send an email from a gmail id to some other id. I was able to produce the output with the code below.
import smtplib
from email.MIMEText import MIMEText
import socket
socket.setdefaulttimeout(None)
HOST = "smtp.gmail.com"
PORT = "587"
sender= "somemail#gmail.com"
password = "pass"
receiver= "receiver#somedomain.com"
msg = MIMEText("Hello World")
msg['Subject'] = 'Subject - Hello World'
msg['From'] = sender
msg['To'] = receiver
server = smtplib.SMTP()
server.connect(HOST, PORT)
server.starttls()
server.login(sender,password)
server.sendmail(sender,receiver, msg.as_string())
server.close()
But I have to do the same without the help of an external SMTP server. How can do the same with Python?
Please help.
The best way to achieve this is understand the Fake SMTP code it uses the great smtpd module.
#!/usr/bin/env python
"""A noddy fake smtp server."""
import smtpd
import asyncore
class FakeSMTPServer(smtpd.SMTPServer):
"""A Fake smtp server"""
def __init__(*args, **kwargs):
print "Running fake smtp server on port 25"
smtpd.SMTPServer.__init__(*args, **kwargs)
def process_message(*args, **kwargs):
pass
if __name__ == "__main__":
smtp_server = FakeSMTPServer(('localhost', 25), None)
try:
asyncore.loop()
except KeyboardInterrupt:
smtp_server.close()
To use this, save the above as fake_stmp.py and:
chmod +x fake_smtp.py
sudo ./fake_smtp.py
If you really want to go into more details, then I suggest that you understand the source code of that module.
If that doesn't work try the smtplib:
import smtplib
SERVER = "localhost"
FROM = "sender#example.com"
TO = ["user#example.com"] # must be a list
SUBJECT = "Hello!"
TEXT = "This message was sent with Python's smtplib."
# Prepare actual message
message = """\
From: %s
To: %s
Subject: %s
%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)
# Send the mail
server = smtplib.SMTP(SERVER)
server.sendmail(FROM, TO, message)
server.quit()
Most likely, you may already have an SMTP server running on the host that you are working on. If you do ls -l /usr/sbin/sendmail does it show that an executable file (or symlink to another file) exists at this location? If so, then you may be able to use this to send outgoing mail. Try /usr/sbin/sendmail recipient#recipientdomain.com < /path/to/file.txt to send the message contained in /path/to/file.txt to recipient#recipientdomain.com (/path/to/file.txt should be an RFC-compliant email message). If that works, then you can use /usr/sbin/sendmail to send mail from your python script - either by opening a handle to /usr/sbin/sendmail and writing the message to it, or simply by executing the above command from your python script by way of a system call.

Choice of SMTP server to send e-mail to myself from Python for logging purposes

The Python logging library provides a class called "SMTPHandler" that will let me e-mail myself the outputs of logging commands. I've some pasted below some example code I found on a (possibly old) website for the library. I can modify it to get it to work with either gmail or my ISP as the SMTP server, but both cases require my password. I currently know of two possible solutions:
I can hardcode my password, which I'd prefer not to do, since this code finds its way onto a cloud revision control server.
I can file my password away in a text file on my machine and have my code read it, which seems ugly. With a more effort I may be able to store the password encrypted, rather than as plaintext.
I'm using a Mac, and I can e-mail myself by running mail on the command line and get the e-mail just fine. I don't know what mail is doing but it may be able to get my SMTP server details from the same place that Mac Mail reads them from and then use the external SMTP server. I tried setting MAILHOST="localhost" in the Python code below and that didn't work.
Is there a better way than #1 or #2 to get these e-mails to my gmail address?
import logging, logging.handlers
MAILHOST = 'beta'
FROM = 'log_test5#yourdomain.com'
TO = ['arkadi_renko']
SUBJECT = 'Test Logging email from Python logging module (non-buffering)'
def main():
log = logging.getLogger("")
log.setLevel(logging.DEBUG)
hdlr = logging.handlers.SMTPHandler(MAILHOST, FROM, TO, SUBJECT)
hdlr.setFormatter(logging.Formatter("%(asctime)s %(levelname)-5s %(message)s"))
log.addHandler(hdlr)
log.info("Test email contents")
log.removeHandler(hdlr)
if __name__ == "__main__":
main()
I needed to do the exact same thing. You can give smtplib a try. Something like
import smtplib
from email.mime.text import MIMEText
msg = MIMEText('YOUR_MESSAGE_BODY')
me = 'YOUR_SOURCE#EMAIL.COM'
you = 'YOUR_TARGET#EMAIL.COM'
msg['Subject'] = 'YOUR_MESSAGE_SUBJECT'
msg['From'] = me
msg['To'] = you
s = smtplib.SMTP('localhost')
s.sendmail(me, [you], msg.as_string())
s.quit()
No password is involved.
If you encounter errors like
...
error: [Errno 61] Connection refused
It probably means you don't have smtp server installed or enabled on your mac, installing postfix (say from macports) should fix that.

Sending email with python smtplib not working, confused about the "from" field

I'm trying to send an email in python. Here is my code.
import smtplib
if __name__ == '__main__':
SERVER = "localhost"
FROM = "sender#example.com"
TO = ["wmh1993#gmail.com"] # must be a list
SUBJECT = "Hello!"
TEXT = "This message was sent with Python's smtplib."
# Prepare actual message
message = """\
From: %s
To: %s
Subject: %s
%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)
# Send the mail
server = smtplib.SMTP(SERVER)
server.sendmail(FROM, TO[0], message)
server.quit()
print "Message sent!"
This runs without error, but no email is sent to wmh1993#gmail.com.
Questions
One thing I don't understand about this code --- what restrictions do I have when setting the FROM field?
Do I somehow have to say that it was from my computer?
What is in place to prevent me from spoofing someone else's email?
Or am I at liberty to do that?
This runs without error, but no email is sent to wmh1993#gmail.com.
This usually means, the message was transferred to your MTA (mailserver) on 'localhost', but this server could not relay it to gmail. it probably tried to send a bounce message to "sender#example.com" and that failed as well. or it sent the message successfully but it landed in gmails spam folder (the message could trigger spam rules since it is missing a date header)
One thing I don't understand about this code --- what restrictions do I have when setting the FROM field?
it must be a syntactically valid email address
Do I somehow have to say that it was from my computer?
no. but that could be the problem why it was not delivered. is your computer on a home/dynamic/dial-up IP? gmail (and many many many other providers) don't accept mail from such IPs. the HELO of your mailserver might be wrong, DNS settings might be incorrect etc. you need to check the server logs. you probably have to configure your local mailserver to relay the message via a smarthost instead of trying to contact the target server directly.
What is in place to prevent me from spoofing someone else's email?
not much, that's why we have so much spam from forged adresses. things like SPF/DKIM can help a bit, but the SMTP protocol itself doesn't offer protection against spoofing.
Or am I at liberty to do that?
technically yes.
Well, since you don't specify exactly what kind of email server you are using and its settings, there are several things that might be wrong here.
First of all, you need to specify the HOST and the PORT of your server and connect to it.
Example:
HOST = "smtp.gmail.com"
PORT = "587"
SERVER = smtplib.SMTP()
SERVER.connect(HOST, PORT)
Then you need to specify an user and his password to this host.
Example:
USER = "myuser#gmail.com"
PASSWD = "123456"
Some servers require the TLS protocol.
Example:
SERVER.starttls()
Then you need to login.
Example:
SERVER.login(USER,PASSWD)
Only then you are able to send the email with your sendmail.
This example works pretty well in most common servers.
If you are using, as it seems, your own server, there aren't much changes you need to apply. But you need to know what kind of requirements this server has.
The "from" field in the email headers specifies the sender's email address. When using smtplib in Python to send an email, the "from" field can be set using the "from_address" argument in the smtplib.SMTP function. Here's an example:
import smtplib
sender_email = "sender#example.com"
recipient_email = "recipient#example.com"
message = "Subject: Example Email\n\nThis is an example email."
with smtplib.SMTP("smtp.example.com", 587) as smtp:
smtp.ehlo()
smtp.starttls()
smtp.login("sender#example.com", "password")
smtp.sendmail(sender_email, recipient_email, message)
Note that many email servers may reject emails that have a "from" address that doesn't match the login credentials.

Categories