Nothing happens when connecting to gmail account using Python - python

I am trying to send an email from my raspberry pi on startup to get its IP address. I followed this blog: https://elinux.org/RPi_Email_IP_On_Boot_Debian
My code:
__author__ = 'author'
__license__ = "license"
__version__ = "1.0"
__maintainer__ = "maintainer"
__status__ = "Test"
import subprocess
import smtplib
from email.mime.text import MIMEText
import datetime
def connect_type(word_list):
""" This function takes a list of words, then, depeding which key word, returns the corresponding
internet connection type as a string. ie) 'ethernet'.
"""
if 'wlan0' in word_list or 'wlan1' in word_list:
con_type = 'wifi'
elif 'eth0' in word_list:
con_type = 'ethernet'
else:
con_type = 'current'
return con_type
# Change to your own account information
# Account Information
to = 'toemail#gmx.com' # Email to send to.
gmail_user = 'myemail#gmail.com' # Email to send from. (MUST BE GMAIL)
gmail_password = 'mypwd' # Gmail password.
try:
smtpserver = smtplib.SMTP('smtp.gmail.com',587) # Server to use.
smtpserver.set_debuglevel(1)
smtpserver.ehlo() # Says 'hello' to the server
smtpserver.starttls() # Start TLS encryption
smtpserver.ehlo()
smtpserver.login(gmail_user, gmail_password) # Log in to server
today = datetime.date.today() # Get current time/date
arg='ip route list' # Linux command to retrieve ip addresses.
# Runs 'arg' in a 'hidden terminal'.
p=subprocess.Popen(arg,shell=True,stdout=subprocess.PIPE)
data = p.communicate() # Get data from 'p terminal'.
# Split IP text block into three, and divide the two containing IPs into words.
ip_lines = data[0].splitlines()
split_line_a = ip_lines[1].split()
split_line_b = ip_lines[2].split()
# con_type variables for the message text. ex) 'ethernet', 'wifi', etc.
ip_type_a = connect_type(split_line_a)
ip_type_b = connect_type(split_line_b)
"""Because the text 'src' is always followed by an ip address,
we can use the 'index' function to find 'src' and add one to
get the index position of our ip.
"""
ipaddr_a = split_line_a[split_line_a.index('src')+1]
ipaddr_b = split_line_b[split_line_b.index('src')+1]
# Creates a sentence for each ip address.
my_ip_a = 'Your %s ip is %s' % (ip_type_a, ipaddr_a)
my_ip_b = 'Your %s ip is %s' % (ip_type_b, ipaddr_b)
# Creates the text, subject, 'from', and 'to' of the message.
msg = MIMEText(my_ip_a + "\n" + my_ip_b)
msg['Subject'] = 'IPs For RaspberryPi on %s' % today.strftime('%b %d %Y')
msg['From'] = gmail_user
msg['To'] = to
# Sends the message
smtpserver.sendmail(gmail_user, [to], msg.as_string())
# Closes the smtp server.
smtpserver.quit()
except Exception as e:
print ("[ERROR] failed to send mail: " + str(e))
when executing the program, no exception occurs. however, the program tries to connect to the server forever at line
smtpserver = smtplib.SMTP('smtp.gmail.com',587)
and nothing happens.
I can reach the smtp server and port using telnet without any problem. I also enabled less secure apps in my Gmail account.
any suggestions?

Related

Hey I want to send email to more than one person with python

Hey i want to send an email to a bunch of people but for some reason even if the output of print is more than one email the program sending the email only to first person of the text what can i do ?
# Import Python Packages
import smtplib
# Set Global Variables
gmail_user = 'your#gmail.com'
gmail_password = 'password'
# Create Email
mail_from = gmail_user
for i in range(2):
with open('C:\\email.txt', 'r', encoding="utf8") as f
mail_to = f.read().rstrip()
mail_subject = 'subject'
mail_message_body = 'body'
mail_message = '''\
From: %s
To: %s
Subject: %s
%s
''' % (mail_from, mail_to, mail_subject, mail_message_body)
# Sent Email
server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
server.login(gmail_user, gmail_password)
server.sendmail(mail_from, mail_to, mail_message)
print(mail_to)
server.close()
Send_to must be a string object having addresses separated by ", ".
example :
send_to='xyz1#gmail.com,hhdasn#yahoo.com'
The line that performs sending of email is server.sendmail(mail_from, mail_to, mail_message). You are calling it once. You can check it by placing print(mail_to) statement next to it.
You need to call sendmail in loop if you want to send email multiple times.

Detect bounced emails in Python smtplib

I'm trying to catch all emails that bounced when sending them via smtplib in Python. I looked at this similar post which suggested adding an exception catcher, but I noticed that my sendmail function doesn't throw any exceptions even for fake email addresses.
Here is my send_email function which uses smtplib.
def send_email(body, subject, recipients, sent_from="myEmail#server.com"):
msg = MIMEText(body)
msg['Subject'] = subject
msg['From'] = sent_from
msg['To'] = ", ".join(recipients)
s = smtplib.SMTP('mySmtpServer:Port')
try:
s.sendmail(msg['From'], recipients, msg.as_string())
except SMTPResponseException as e:
error_code = e.smtp_code
error_message = e.smtp_error
print("error_code: {}, error_message: {}".format(error_code, error_message))
s.quit()
Sample call:
send_email("Body-Test", "Subject-Test", ["fakejfdklsa#jfdlsaf.com"], "myemail#server.com")
Since I set the sender as myself, I am able to receive the email bounce report in my sender's inbox:
<fakejfdklsa#jfdlsaf.com>: Host or domain name not found. Name service error
for name=jfdlsaf.com type=A: Host not found
Final-Recipient: rfc822; fakejfdklsa#jfdlsaf.com
Original-Recipient: rfc822;fakejfdklsa#jfdlsaf.com
Action: failed
Status: 5.4.4
Diagnostic-Code: X-Postfix; Host or domain name not found. Name service error
for name=jfdlsaf.com type=A: Host not found
Is there a way to get the bounce message through Python?
import poplib
from email import parser
#breaks with if this is left out for some reason (MAXLINE is set too low by default.)
poplib._MAXLINE=20480
pop_conn = poplib.POP3_SSL('your pop server',port)
pop_conn.user(username)
pop_conn.pass_(password)
#Get messages from server:
messages = [pop_conn.retr(i) for i in range(1, len(pop_conn.list()[1]) + 1)]
# Concat message pieces:
messages = ["\n".join(mssg[1]) for mssg in messages]
#Parse message intom an email object:
messages = [parser.Parser().parsestr(mssg) for mssg in messages]
for message in messages:
if "Undeliverable" in message['subject']:
print message['subject']
for part in message.walk():
if part.get_content_type():
body = str(part.get_payload(decode=True))
bounced = re.findall('[a-z0-9-_\.]+#[a-z0-9-\.]+\.[a-z\.]{2,5}',body)
if bounced:
bounced = str(bounced[0].replace(username,''))
if bounced == '':
break
print bounced
Hope this helps. This will check the contents of the mailbox for any undeliverable reports and read the message to find the email address that bounced.It then prints the result
You can use this function for gmail, basically checking the inbox that whether there is any email from Mail Delivery Subsystem with particular Text in body
def is_email_bounced(email, app_password, email_in_question):
obj = imaplib.IMAP4_SSL('imap.gmail.com',993)
obj.login(email, app_password)
obj.select() # Default Inbox
typ, data = obj.search(None, f'(TEXT "{email_in_question}") (Subject "Delivery Status Notification (Failure)")')
try: data.remove(b'')
except: pass
if len(data) >= 1: return True
else: return False
run this function after sending the email, and check whether email got bounced or not
e.g.
send_email("Body-Test", "Subject-Test", ["fakejfdklsa#jfdlsaf.com"], "myemail#server.com")
if is_email_bounced("youremail#gmail.com", "app_password", "email_in_ques_404#gmail.com"):
print("Email Bounced")
Change email Subject "Delivery Status Notification (Failure)" as per your email service provider, for this code, I've considered email provider as gmail

sending email using python using smtp

I am trying to send an email using SMTP via python.
This is my code:
import smtplib
from email.mime.text import MIMEText
textfile='msg.txt'
you='ashwin#gmail.com'
me='ashwin#gmail.com'
fp = open(textfile, 'rb')
msg = MIMEText(fp.read())
fp.close()
# me == the sender's email address
# you == the recipient's email address
msg['Subject'] = 'The contents of %s' % textfile
msg['From'] = me
msg['To'] = you
print "reached before s"
s = smtplib.SMTP('127.0.0.1',8000)
print "reached after s"
s.sendmail(me, [you], msg.as_string())
s.quit()
when I try and execute this code, "reached before s" is printed and then goes into an infinite loop or so, i.e. "reached after s" is not printed and the program is still running.
This is code for the server:
import sys
import BaseHTTPServer
from SimpleHTTPServer import SimpleHTTPRequestHandler
HandlerClass = SimpleHTTPRequestHandler
ServerClass = BaseHTTPServer.HTTPServer
Protocol = "HTTP/1.0"
if sys.argv[1:]:
port = int(sys.argv[1])
else:
port = 8000
server_address = ('127.0.0.1', port)
HandlerClass.protocol_version = Protocol
httpd = ServerClass(server_address, HandlerClass)
sa = httpd.socket.getsockname()
print "Serving HTTP on", sa[0], "port", sa[1], "..."
httpd.serve_forever()
can someone figure out what is wrong?
I believe yagmail (disclaimer: I'm the maintainer) can be of great help to you.
Its goal is to make it easy to send emails with attachments.
import yagmail
yag = yagmail.SMTP('ashwin#gmail.com', 'yourpassword')
yag.send(to = 'ashwin#gmail.com', subject ='The contents of msg.txt', contents = 'msg.txt')
That's only three lines indeed.
Note that yagmail contents will try to load the string passed. If it cannot, it will send as text, if it can load it, it will attach it.
If you pass a list of strings, it will try to load each string as a file (or, again, just display the text).
Install with pip install yagmail or pip3 install yagmail for Python 3.
More info at github.
Here is a different approach that creates an email sender class with all the error handling taken care of:
import getpass
import smtplib
class EmailBot(object):
# Gets the username and password and sets up the Gmail connection
def __init__(self):
self.username = \
raw_input('Please enter your Gmail address and hit Enter: ')
self.password = \
getpass.getpass('Please enter the password for this email account and hit Enter: ')
self.server = 'smtp.gmail.com'
self.port = 587
print 'Connecting to the server. Please wait a moment...'
try:
self.session = smtplib.SMTP(self.server, self.port)
self.session.ehlo() # Identifying ourself to the server
self.session.starttls() # Puts the SMTP connection in TLS mode. All SMTP commands that follow will be encrypted
self.session.ehlo()
except smtplib.socket.gaierror:
print 'Error connecting. Please try running the program again later.'
sys.exit() # The program will cleanly exit in such an error
try:
self.session.login(self.username, self.password)
del self.password
except smtplib.SMTPAuthenticationError:
print 'Invalid username (%s) and/or password. Please try running the program again later.'\
% self.username
sys.exit() # program will cleanly exit in such an error
def send_message(self, subject, body):
try:
headers = ['From: ' + self.username, 'Subject: ' + subject,
'To: ' + self.username, 'MIME-Version: 1.0',
'Content-Type: text/html']
headers = '\r\n'.join(headers)
self.session.sendmail(self.username, self.username, headers + '''\r\r''' + body)
except smtplib.socket.timeout:
print 'Socket error while sending message. Please try running the program again later.'
sys.exit() # Program cleanly exits
except:
print "Couldn't send message. Please try running the program again later."
sys.exit() # Program cleanly exits
All you need to do is create an EmailBot instance and call the send_message method on it, with the appropriate details as inputs.

Send Outlook Email Via Python?

I am using Outlook 2003.
What is the best way to send email (through Outlook 2003) using Python?
import win32com.client as win32
outlook = win32.Dispatch('outlook.application')
mail = outlook.CreateItem(0)
mail.To = 'To address'
mail.Subject = 'Message subject'
mail.Body = 'Message body'
mail.HTMLBody = '<h2>HTML Message body</h2>' #this field is optional
# To attach a file to the email (optional):
attachment = "Path to the attachment"
mail.Attachments.Add(attachment)
mail.Send()
Will use your local outlook account to send.
Note if you are trying to do something not mentioned above, look at the COM docs properties/methods: https://msdn.microsoft.com/en-us/vba/outlook-vba/articles/mailitem-object-outlook. In the code above, mail is a MailItem Object.
For a solution that uses outlook see TheoretiCAL's answer.
Otherwise, use the smtplib that comes with python. Note that this will require your email account allows smtp, which is not necessarily enabled by default.
SERVER = "smtp.example.com"
FROM = "yourEmail#example.com"
TO = ["listOfEmails"] # must be a list
SUBJECT = "Subject"
TEXT = "Your Text"
# Prepare actual message
message = """From: %s\r\nTo: %s\r\nSubject: %s\r\n\
%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)
# Send the mail
import smtplib
server = smtplib.SMTP(SERVER)
server.sendmail(FROM, TO, message)
server.quit()
EDIT: this example uses reserved domains like described in RFC2606
SERVER = "smtp.example.com"
FROM = "johnDoe#example.com"
TO = ["JaneDoe#example.com"] # must be a list
SUBJECT = "Hello!"
TEXT = "This is a test of emailing through smtp of example.com."
# Prepare actual message
message = """From: %s\r\nTo: %s\r\nSubject: %s\r\n\
%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)
# Send the mail
import smtplib
server = smtplib.SMTP(SERVER)
server.login("MrDoe", "PASSWORD")
server.sendmail(FROM, TO, message)
server.quit()
For it to actually work with gmail, Mr. Doe will need to go to the options tab in gmail and set it to allow smtp connections.
Note the addition of the login line to authenticate to the remote server. The original version does not include this, an oversight on my part.
I wanted to send email using SMTPLIB, its easier and it does not require local setup. After other answers were not directly helpful, This is what i did.
Open Outlook in a browser; Go to the top right corner, click the gear icon for Settings, Choose 'Options' from the appearing drop-down list.
Go to 'Accounts', click 'Pop and Imap',
You will see the option: "Let devices and apps use pop",
Choose Yes option and Save changes.
Here is the code there after; Edit where neccesary.
Most Important thing is to enable POP and the server code herein;
import smtplib
body = 'Subject: Subject Here .\nDear ContactName, \n\n' + 'Email\'s BODY text' + '\nYour :: Signature/Innitials'
try:
smtpObj = smtplib.SMTP('smtp-mail.outlook.com', 587)
except Exception as e:
print(e)
smtpObj = smtplib.SMTP_SSL('smtp-mail.outlook.com', 465)
#type(smtpObj)
smtpObj.ehlo()
smtpObj.starttls()
smtpObj.login('me#outlook.com', "password")
smtpObj.sendmail('sender#outlook.com', 'recipient#gmail.com', body) # Or recipient#outlook
smtpObj.quit()
pass
using pywin32:
from win32com.client import Dispatch
session = Dispatch('MAPI.session')
session.Logon('','',0,1,0,0,'exchange.foo.com\nUserName');
msg = session.Outbox.Messages.Add('Hello', 'This is a test')
msg.Recipients.Add('Corey', 'SMTP:corey#foo.com')
msg.Send()
session.Logoff()
A simple solution for Office 365 is
from O365 import Message
html_template = """
<html>
<head>
<title></title>
</head>
<body>
{}
</body>
</html>
"""
final_html_data = html_template.format(df.to_html(index=False))
o365_auth = ('sender_username#company_email.com','Password')
m = Message(auth=o365_auth)
m.setRecipients('receiver_username#company_email.com')
m.setSubject('Weekly report')
m.setBodyHTML(final)
m.sendMessage()
Here df is a dataframe converted to an html Table, which is being injected into html_template
This is a pretty old question but there is one more solution. The current Outlook SMTP server is (as of 2022):
Host: smtp.office365.com
Port: 587 (for TLS)
Probably the easiest and cleanest solution is to use Red Mail that has these already set:
pip install redmail
Then:
from redmail import outlook
outlook.user_name = "example#hotmail.com"
outlook.password = "<MY PASSWORD>"
outlook.send(
receivers=["you#example.com"],
subject="An example",
text="Hi, this is an example."
)
Red Mail supports all sorts of advanced features:
HTML and text bodies
Attachments from various types
Embedded images
It also has Jinja support
Links:
Documentation: https://red-mail.readthedocs.io/en/latest/
Source code: https://github.com/Miksus/red-mail
Disclaimer: I'm the author
Other than win32, if your company had set up you web outlook, you can also try PYTHON REST API, which is officially made by Microsoft. (https://msdn.microsoft.com/en-us/office/office365/api/mail-rest-operations)
This was one I tried using Win32:
import win32com.client as win32
import psutil
import os
import subprocess
import sys
# Drafting and sending email notification to senders. You can add other senders' email in the list
def send_notification():
outlook = win32.Dispatch('outlook.application')
olFormatHTML = 2
olFormatPlain = 1
olFormatRichText = 3
olFormatUnspecified = 0
olMailItem = 0x0
newMail = outlook.CreateItem(olMailItem)
newMail.Subject = sys.argv[1]
#newMail.Subject = "check"
newMail.BodyFormat = olFormatHTML #or olFormatRichText or olFormatPlain
#newMail.HTMLBody = "test"
newMail.HTMLBody = sys.argv[2]
newMail.To = "xyz#abc.com"
attachment1 = sys.argv[3]
attachment2 = sys.argv[4]
newMail.Attachments.Add(attachment1)
newMail.Attachments.Add(attachment2)
newMail.display()
# or just use this instead of .display() if you want to send immediately
newMail.Send()
# Open Outlook.exe. Path may vary according to system config
# Please check the path to .exe file and update below
def open_outlook():
try:
subprocess.call(['C:\Program Files\Microsoft Office\Office15\Outlook.exe'])
os.system("C:\Program Files\Microsoft Office\Office15\Outlook.exe");
except:
print("Outlook didn't open successfully")
#
# Checking if outlook is already opened. If not, open Outlook.exe and send email
for item in psutil.pids():
p = psutil.Process(item)
if p.name() == "OUTLOOK.EXE":
flag = 1
break
else:
flag = 0
if (flag == 1):
send_notification()
else:
open_outlook()
send_notification()

Sending mail from Python using SMTP

I'm using the following method to send mail from Python using SMTP. Is it the right method to use or are there gotchas I'm missing ?
from smtplib import SMTP
import datetime
debuglevel = 0
smtp = SMTP()
smtp.set_debuglevel(debuglevel)
smtp.connect('YOUR.MAIL.SERVER', 26)
smtp.login('USERNAME#DOMAIN', 'PASSWORD')
from_addr = "John Doe <john#doe.net>"
to_addr = "foo#bar.com"
subj = "hello"
date = datetime.datetime.now().strftime( "%d/%m/%Y %H:%M" )
message_text = "Hello\nThis is a mail from your server\n\nBye\n"
msg = "From: %s\nTo: %s\nSubject: %s\nDate: %s\n\n%s"
% ( from_addr, to_addr, subj, date, message_text )
smtp.sendmail(from_addr, to_addr, msg)
smtp.quit()
The script I use is quite similar; I post it here as an example of how to use the email.* modules to generate MIME messages; so this script can be easily modified to attach pictures, etc.
I rely on my ISP to add the date time header.
My ISP requires me to use a secure smtp connection to send mail, I rely on the smtplib module (downloadable at http://www1.cs.columbia.edu/~db2501/ssmtplib.py)
As in your script, the username and password, (given dummy values below), used to authenticate on the SMTP server, are in plain text in the source. This is a security weakness; but the best alternative depends on how careful you need (want?) to be about protecting these.
=======================================
#! /usr/local/bin/python
SMTPserver = 'smtp.att.yahoo.com'
sender = 'me#my_email_domain.net'
destination = ['recipient#her_email_domain.com']
USERNAME = "USER_NAME_FOR_INTERNET_SERVICE_PROVIDER"
PASSWORD = "PASSWORD_INTERNET_SERVICE_PROVIDER"
# typical values for text_subtype are plain, html, xml
text_subtype = 'plain'
content="""\
Test message
"""
subject="Sent from Python"
import sys
import os
import re
from smtplib import SMTP_SSL as SMTP # this invokes the secure SMTP protocol (port 465, uses SSL)
# from smtplib import SMTP # use this for standard SMTP protocol (port 25, no encryption)
# old version
# from email.MIMEText import MIMEText
from email.mime.text import MIMEText
try:
msg = MIMEText(content, text_subtype)
msg['Subject']= subject
msg['From'] = sender # some SMTP servers will do this automatically, not all
conn = SMTP(SMTPserver)
conn.set_debuglevel(False)
conn.login(USERNAME, PASSWORD)
try:
conn.sendmail(sender, destination, msg.as_string())
finally:
conn.quit()
except:
sys.exit( "mail failed; %s" % "CUSTOM_ERROR" ) # give an error message
The method I commonly use...not much different but a little bit
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
msg = MIMEMultipart()
msg['From'] = 'me#gmail.com'
msg['To'] = 'you#gmail.com'
msg['Subject'] = 'simple email in python'
message = 'here is the email'
msg.attach(MIMEText(message))
mailserver = smtplib.SMTP('smtp.gmail.com',587)
# identify ourselves to smtp gmail client
mailserver.ehlo()
# secure our email with tls encryption
mailserver.starttls()
# re-identify ourselves as an encrypted connection
mailserver.ehlo()
mailserver.login('me#gmail.com', 'mypassword')
mailserver.sendmail('me#gmail.com','you#gmail.com',msg.as_string())
mailserver.quit()
That's it
Also if you want to do smtp auth with TLS as opposed to SSL then you just have to change the port (use 587) and do smtp.starttls(). This worked for me:
...
smtp.connect('YOUR.MAIL.SERVER', 587)
smtp.ehlo()
smtp.starttls()
smtp.ehlo()
smtp.login('USERNAME#DOMAIN', 'PASSWORD')
...
Make sure you don't have any firewalls blocking SMTP. The first time I tried to send an email, it was blocked both by Windows Firewall and McAfee - took forever to find them both.
What about this?
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()
The main gotcha I see is that you're not handling any errors: .login() and .sendmail() both have documented exceptions that they can throw, and it seems like .connect() must have some way to indicate that it was unable to connect - probably an exception thrown by the underlying socket code.
following code is working fine for me:
import smtplib
to = 'mkyong2002#yahoo.com'
gmail_user = 'mkyong2002#gmail.com'
gmail_pwd = 'yourpassword'
smtpserver = smtplib.SMTP("smtp.gmail.com",587)
smtpserver.ehlo()
smtpserver.starttls()
smtpserver.ehlo()
smtpserver.login(gmail_user, gmail_pwd)
header = 'To:' + to + '\n' + 'From: ' + gmail_user + '\n' + 'Subject:testing \n'
print header
msg = header + '\n this is test msg from mkyong.com \n\n'
smtpserver.sendmail(gmail_user, to, msg)
print 'done!'
smtpserver.quit()
Ref: http://www.mkyong.com/python/how-do-send-email-in-python-via-smtplib/
The example code which i did for send mail using SMTP.
import smtplib, ssl
smtp_server = "smtp.gmail.com"
port = 587 # For starttls
sender_email = "sender#email"
receiver_email = "receiver#email"
password = "<your password here>"
message = """ Subject: Hi there
This message is sent from Python."""
# Create a secure SSL context
context = ssl.create_default_context()
# Try to log in to server and send email
server = smtplib.SMTP(smtp_server,port)
try:
server.ehlo() # Can be omitted
server.starttls(context=context) # Secure the connection
server.ehlo() # Can be omitted
server.login(sender_email, password)
server.sendmail(sender_email, receiver_email, message)
except Exception as e:
# Print any error messages to stdout
print(e)
finally:
server.quit()
You should make sure you format the date in the correct format - RFC2822.
See all those lenghty answers? Please allow me to self promote by doing it all in a couple of lines.
Import and Connect:
import yagmail
yag = yagmail.SMTP('john#doe.net', host = 'YOUR.MAIL.SERVER', port = 26)
Then it is just a one-liner:
yag.send('foo#bar.com', 'hello', 'Hello\nThis is a mail from your server\n\nBye\n')
It will actually close when it goes out of scope (or can be closed manually). Furthermore, it will allow you to register your username in your keyring such that you do not have to write out your password in your script (it really bothered me prior to writing yagmail!)
For the package/installation, tips and tricks please look at git or pip, available for both Python 2 and 3.
you can do like that
import smtplib
from email.mime.text import MIMEText
from email.header import Header
server = smtplib.SMTP('mail.servername.com', 25)
server.ehlo()
server.starttls()
server.login('username', 'password')
from = 'me#servername.com'
to = 'mygfriend#servername.com'
body = 'That A Message For My Girl Friend For tell Him If We will go to eat Something This Nigth'
subject = 'Invite to A Diner'
msg = MIMEText(body,'plain','utf-8')
msg['Subject'] = Header(subject, 'utf-8')
msg['From'] = Header(from, 'utf-8')
msg['To'] = Header(to, 'utf-8')
message = msg.as_string()
server.sendmail(from, to, message)
Based on this example I made following function:
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
def send_email(host, port, user, pwd, recipients, subject, body, html=None, from_=None):
""" copied and adapted from
https://stackoverflow.com/questions/10147455/how-to-send-an-email-with-gmail-as-provider-using-python#12424439
returns None if all ok, but if problem then returns exception object
"""
PORT_LIST = (25, 587, 465)
FROM = from_ if from_ else user
TO = recipients if isinstance(recipients, (list, tuple)) else [recipients]
SUBJECT = subject
TEXT = body.encode("utf8") if isinstance(body, unicode) else body
HTML = html.encode("utf8") if isinstance(html, unicode) else html
if not html:
# Prepare actual message
message = """From: %s\nTo: %s\nSubject: %s\n\n%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)
else:
# https://stackoverflow.com/questions/882712/sending-html-email-using-python#882770
msg = MIMEMultipart('alternative')
msg['Subject'] = SUBJECT
msg['From'] = FROM
msg['To'] = ", ".join(TO)
# Record the MIME types of both parts - text/plain and text/html.
# utf-8 -> https://stackoverflow.com/questions/5910104/python-how-to-send-utf-8-e-mail#5910530
part1 = MIMEText(TEXT, 'plain', "utf-8")
part2 = MIMEText(HTML, 'html', "utf-8")
# Attach parts into message container.
# According to RFC 2046, the last part of a multipart message, in this case
# the HTML message, is best and preferred.
msg.attach(part1)
msg.attach(part2)
message = msg.as_string()
try:
if port not in PORT_LIST:
raise Exception("Port %s not one of %s" % (port, PORT_LIST))
if port in (465,):
server = smtplib.SMTP_SSL(host, port)
else:
server = smtplib.SMTP(host, port)
# optional
server.ehlo()
if port in (587,):
server.starttls()
server.login(user, pwd)
server.sendmail(FROM, TO, message)
server.close()
# logger.info("SENT_EMAIL to %s: %s" % (recipients, subject))
except Exception, ex:
return ex
return None
if you pass only body then plain text mail will be sent, but if you pass html argument along with body argument, html email will be sent (with fallback to text content for email clients that don't support html/mime types).
Example usage:
ex = send_email(
host = 'smtp.gmail.com'
#, port = 465 # OK
, port = 587 #OK
, user = "xxx#gmail.com"
, pwd = "xxx"
, from_ = 'xxx#gmail.com'
, recipients = ['yyy#gmail.com']
, subject = "Test from python"
, body = "Test from python - body"
)
if ex:
print("Mail sending failed: %s" % ex)
else:
print("OK - mail sent"
Btw. If you want to use gmail as testing or production SMTP server,
enable temp or permanent access to less secured apps:
login to google mail/account
go to: https://myaccount.google.com/lesssecureapps
enable
send email using this function or similar
(recommended) go to: https://myaccount.google.com/lesssecureapps
(recommended) disable
Or
import smtplib
from email.message import EmailMessage
from getpass import getpass
password = getpass()
message = EmailMessage()
message.set_content('Message content here')
message['Subject'] = 'Your subject here'
message['From'] = "USERNAME#DOMAIN"
message['To'] = "you#mail.com"
try:
smtp_server = None
smtp_server = smtplib.SMTP("YOUR.MAIL.SERVER", 587)
smtp_server.ehlo()
smtp_server.starttls()
smtp_server.ehlo()
smtp_server.login("USERNAME#DOMAIN", password)
smtp_server.send_message(message)
except Exception as e:
print("Error: ", str(e))
finally:
if smtp_server is not None:
smtp_server.quit()
If you want to use Port 465 you have to create an SMTP_SSL object.
Here's a working example for Python 3.x
#!/usr/bin/env python3
from email.message import EmailMessage
from getpass import getpass
from smtplib import SMTP_SSL
from sys import exit
smtp_server = 'smtp.gmail.com'
username = 'your_email_address#gmail.com'
password = getpass('Enter Gmail password: ')
sender = 'your_email_address#gmail.com'
destination = 'recipient_email_address#gmail.com'
subject = 'Sent from Python 3.x'
content = 'Hello! This was sent to you via Python 3.x!'
# Create a text/plain message
msg = EmailMessage()
msg.set_content(content)
msg['Subject'] = subject
msg['From'] = sender
msg['To'] = destination
try:
s = SMTP_SSL(smtp_server)
s.login(username, password)
try:
s.send_message(msg)
finally:
s.quit()
except Exception as E:
exit('Mail failed: {}'.format(str(E)))
What about Red Mail?
Install it:
pip install redmail
Then just:
from redmail import EmailSender
# Configure the sender
email = EmailSender(
host="YOUR.MAIL.SERVER",
port=26,
username='me#example.com',
password='<PASSWORD>'
)
# Send an email:
email.send(
subject="An example email",
sender="me#example.com",
receivers=['you#example.com'],
text="Hello!",
html="<h1>Hello!</h1>"
)
It has quite a lot of features:
Email attachments from various sources
Embedding images and plots to the HTML body
Templating emails with Jinja
Preconfigured Gmail and Outlook
Logging handler
Flask extension
Links:
Source code
Documentation
Releases
Based on madman2890, updated a few things as well as removed the need for mailserver.quit()
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
msg = MIMEMultipart()
msg['From'] = 'me#gmail.com'
msg['To'] = 'you#gmail.com'
msg['Subject'] = 'simple email in python'
message = 'here is the email'
msg.attach(MIMEText(message))
with smtplib.SMTP('smtp-mail.outlook.com',587) as mail_server:
# identify ourselves to smtp gmail client
mail_server.ehlo()
# secure our email with tls encryption
mail_server.starttls()
# re-identify ourselves as an encrypted connection
mail_server.ehlo()
mail_server.login('me#gmail.com', 'mypassword')
mail_server.sendmail('me#gmail.com','you#gmail.com',msg.as_string())

Categories