attach excel file to email using python - python

I am trying to send an excel file via email but somehow the format and text is altered. I am using python3 and MIMEMultipart().
message = MIMEMultipart()
message["From"] = sender_email
message["To"] = receiver_email
message["Subject"] = subject
message.attach(MIMEText(body, "plain"))
filename = "file_name.xlsx" # In same directory as script
# Open PDF file in binary mode
with open(filename, 'r') as attachment:
part = MIMEBase("application", "octet-stream")
part.set_payload(attachment.read())
encoders.encode_base64(part)
message.attach(part)
text = message.as_string()
# Log in to server using secure context and send email
context = ssl.create_default_context()
with smtplib.SMTP_SSL(smtp_server, 465 , context=context) as server:
server.login(sender_email, password)
server.sendmail(sender_email, receiver_email, text)

The comment is wrong; you are not opening the file in binary mode ('rb') and so you are basically corrupting it
Following up on my answer to your previous question, here is a refactored version of your code to use the modern, Python 3.6+ EmailMessage library instead.
from email.message import EmailMessage
...
message = EmailMessage()
message["From"] = sender_email
message["To"] = receiver_email
message["Subject"] = subject
message.set_content(body, 'plain')
# The OS will look in the current working directory, not in the directory where you saved the script
filename = "file_name.xlsx"
# Notice 'rb'
with open(filename, 'rb') as attachment:
message.add_attachment(
attachment.read(),
maintype='application', subtype='octet-stream')
# AGAIN, no need for a context if you are just using the default SSL
with smtplib.SMTP_SSL(smtp_server, 465) as server:
server.login(sender_email, password)
# AGAIN, prefer the modern send_message method
server.send_message(message)
As you notice, there's quite a lot less boilerplate than with the older Email.Message API from Python 3.5 or earlier.
A common arrangement is to have a multipart/related message with body text and an attachment, but the body text represented as a multipart/alternative structure with both a text/plain and a text/html rendering of the message. If you want this, the "asparagus" example from the email module documentation's examples page contains a recipe which demonstrates that (though it also includes an image instead of a binary attachment, and displays it inline in the HTML attachment).
Tangentially, you might be better off choosing a less clunky format than Excel for sharing data. If it's just a table, a CSV text file would be a lot smaller as well as easier to process on the receiving end. (If you do send Excel, probably actually use its designated MIME type rather than the generic application/octet-stream.)

Related

send HTMLbody from file using python

I can send the plain text but unable to send html text in html format.
import email, smtplib, ssl
import os
from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
body = """
this is first mail by using python
"""
port_email = 587
smtp_server = "smtp.gmail.com"
password = "your password"
subject = "An email with attachment from Python"
sender_email = "sender#gmail.example.com"
receiver_email = "receiver#example.net"
# Create a multipart message and set headers
message = MIMEMultipart()
message["From"] = sender_email
message["To"] = receiver_email
message["Subject"] = subject
message["Bcc"] = receiver_email # Recommended for mass emails
# Add body to email
message.attach(MIMEText(body, "plain"))
filename = "file name" # In same directory as script
with open(filename.html, 'r', encoding="utf-8") as attachment:
part1 = attachment.read()
part2 = MIMEText(part1, "html")
message.attach(part2)
text = message.as_string()
context = ssl.create_default_context()
with smtplib.SMTP_SSL(smtp_server, 465 , context=context) as server:
server.login(sender_email, password)
server.sendmail(sender_email, receiver_email, text)
This will send attach file but i want to see the html text in email body.
filename is content html table so code should send the html text which will automatic available in html body with html table.
Why are you passing a bogus body if that's not what you want?
Your code seems to be written for Python 3.5 or earlier. The email library was overhauled in 3.6 and is now quite a bit more versatile and logical. Probably throw away what you have and start over with the examples from the email documentation.
Here's a brief attempt.
from email.message import EmailMessage
...
message = EmailMessage()
message["From"] = sender_email
message["To"] = receiver_email
message["Subject"] = subject
# No point in using Bcc if the recipient is already in To:
with open(filename) as fp:
message.set_content(fp.read(), 'html')
# no need for a context if you are just using the default SSL
with smtplib.SMTP_SSL(smtp_server, 465) as server:
server.login(sender_email, password)
# Prefer the modern send_message method
server.send_message(message)
If you want to send a message in both plain text and HTML, the linked examples show you how to adapt the code to do that, but then really, the text/plain body part should actually contain a useful message, not just a placeholder.
As commented in the code, there is no reason to use Bcc: if you have already specified the recipient in the To: header. If you want to use Bcc: you will have to put something else in the To: header, commonly your own address or an address list like :undisclosed-recipients;
Tangentially, when opening a file, Python (or in fact the operating system) examines the user's current working directory, not the directory from which the Python script was loaded. Perhaps see also What exactly is current working directory?
Mime has a variety of formats. By default MIMEMultipart builds a multipart/mixed message, meaning a simple text body and a bunch of attachments.
When you want an HTML representation of the body, you want a multipart/alternative message:
...
message = MIMEMultipart('alternative')
...
But you are using the old compat32 API. Since Python 3.6 you'd better use email.message.EmailMessage...

Any attachement to email needs to be saved by recipient in right format

I have this problem that I cannot find an answer to. I am sending an email using smtp and I manage to send my email with the required attachement using the following code (all sensitive information is read from a config.json file):
message = MIMEMultipart()
message['From'] = sender_address
message['To'] = receiver_address
message['Subject'] = 'Här kommer veckans zip-fil.'
message.attach(MIMEText(mail_content, 'plain'))
attach_file_name = 'C:/..../downloads/Send_20210201_zipped.zip'
attach_file = open(attach_file_name, 'rb')
payload = MIMEBase('application', 'octate-stream')
payload.set_payload((attach_file).read())
encoders.encode_base64(payload)
payload.add_header('Content-Decomposition', 'attachment', filename=attach_file_name)
message.attach(payload)
session = smtplib.SMTP(server, port)
text = message.as_string()
session.sendmail(sender_address, receiver_address, text)
session.quit()
print('Mailet har skickats')
Now, the email is sent and recieved. BUT, it arrives as an unspecified file with the name ATT0001. At first, I thought it was trash but I discovered that if I save it as ATT0001.zip and open it from where I saved it, it actually is the zip-file I sent. I tested with other types of files and it is the same thing.
What am I doing wrong? How can I ensure the recipient of the files simply needs to save the file without having to know its format?
I did not give up on my own efforts to solve the problem and managed to solve it on my own. I choose to not delete the question and instead to share my own findings. I replaced the MIMEBase part of the got I share with something including MIMEApplication. I also specified the attachement type in the file I shared with the recipient. Here is the complete code. If anyone sees improvements, please do share your input.
message = MIMEMultipart()
message['From'] = sender_address
message['To'] = receiver_address
message['Subject'] = 'The subject of this mail'
message.attach(MIMEText(mail_content, 'plain'))
attach_file_name = file_to_send
file_name_sent = File_sent
attach_file = open(attach_file_name, 'rb')
body_part = MIMEText(mail_content, 'plain')
message.attach(body_part)
with open(attach_file_name,'rb') as file:
message.attach(MIMEApplication(file.read(), Name=file_name_sent +'.zip'))
text = message.as_string()
session = smtplib.SMTP(server, port)
session.starttls()
session.sendmail(sender_address, receiver_address, text)
session.quit()
print('Mailet har skickats')
where sender_address, receiver_address, server, port are all given in a config.json file while file_to_send and file_sent are declared before the mail-part given here while body_part is a standard message. This is meant to be automated so they need to change every week.

Email and smtplib modules in Python - some basic emailing questions

I've just started learning Python and I'm trying to code a bot where it emails a HTML message along with a .docx (Microsoft Word) attachment. Here's my code and it works fine, but I'm confused with a few of the parameters.
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
import os
#Email Variables
myemail = "myemail#hotmail.com"
recipient = "recipientemail#hotmail.com"
#Specifying MIME variables to include in email header
mime_details = MIMEMultipart('mixed')
mime_details['Subject'] = "This is my email subject!"
mime_details['From'] = myemail
mime_details['To'] = recipient
#Creating body of message
html_body = """\
<html>\
<p>\
My email message!
</p>\
</html>\
"""
#Attaching File To Email
os.chdir('C:\\Users\Kyle\Desktop\')
openfile = open('testfile.docx', 'rb')
doc = MIMEApplication(openfile.read(), _subtype='vnd.openxmlformats-officedocument.wordprocessingml.document')
doc.add_header('Content-Disposition', 'attachment', filename='My Content.docx')
mime_details.attach(doc)
openfile.close()
#Recording MIME types of email parts
htmlpart = MIMEText(html_body, _subtype='html')
#Attaching parts to message container
mime_details.attach(htmlpart)
#Sending message via SMTP server
s = smtplib.SMTP(host='smtp.live.com', port=587)
s.ehlo()
s.starttls()
s.login(myemail, 'password')
s.sendmail(myemail, recipient, mime_details.as_string())
s.quit()
I have a few questions regarding the code above, and I would greatly appreciate it if you can help me clear whatever confused thoughts I have regarding the modules above.
A) The add_header module
mime_details['Subject'] = "This is my email subject!"
mime_details['From'] = myemail
mime_details['To'] = recipient
As you can see from the snippet above, I clearly defined each header variable in the MIMEMultipart envelope. According to Python's docs, these values will be added to the header directly. I tried using the add_header() method directly as an alternative, something like:
mime_details.add_header(Subject = "This is my email subject!", To = recipient, From = myemail)
But it gave me errors. Any idea why?
B) At the last few lines of my code, I had to append a .as_string() to the payload I was sending. I tried taking it out but it gave me a TypeError: expected string or buffer.
The Python docs give me this:
as_string(unixfrom=False, maxheaderlen=0, policy=None)
Return the entire message flattened as a string.
I assume that I have to append this in every case? the mime_details object has two parts to it - the HTML message and the .docx file. Both will be converted to strings? What about image files?
C) When I open my file to attach, I read it in 'rb' mode.
Here's the code:
openfile = open('testfile.docx', 'rb')
I tried using 'r' but it raises an error. I've read up on this and 'rb' mode simply opens the file in binary. Why would it make sense to open a .docx file in binary mode? Am I to use 'rb' mode for ALL non.txt files?
D) Finally, I've seen some people use base64 encoding for attachments. I've searched around and a particularly popular script over here is below (from How to send email attachments with Python):
import smtplib, os
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email.utils import COMMASPACE, formatdate
from email import encoders
def send_mail( send_from, send_to, subject, text, files=[], server="localhost", port=587, username='', password='', isTls=True):
msg = MIMEMultipart()
msg['From'] = send_from
msg['To'] = COMMASPACE.join(send_to)
msg['Date'] = formatdate(localtime = True)
msg['Subject'] = subject
msg.attach( MIMEText(text) )
for f in files:
part = MIMEBase('application', "octet-stream")
part.set_payload( open(f,"rb").read() )
encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="{0}"'.format(os.path.basename(f)))
msg.attach(part)
smtp = smtplib.SMTP(server, port)
if isTls: smtp.starttls()
smtp.login(username,password)
smtp.sendmail(send_from, send_to, msg.as_string())
smtp.quit()
Why does content need to be encoded in base64? Does this apply to all files and is a general thing to be added, or can I ignore this? What situations am I to invoke that method?
Finally, being a noob at Python, some of my code above may be redundant\badly structured. If you have any tips\suggestions on how I can improve my simply script, please do let me know.
Thank you!

how to send email attachement using python 2.7

I am getting error when using this code to send email using localhost ip, any suggestion how to solve the socket error?
def SendTMail(self):
# Import the email modules we'll need
# Open a plain text file for reading. For this example, assume that
# the text file contains only ASCII characters.
#try:
fp = open('testint.txt', 'rb')
# Create a text/plain message
msg = MIMEText(fp.read())
testfile = 'TESTING REPORT'
fp.close()
me = '124#hotmail.co.uk'
you = '123#live.com'
msg['Subject'] = 'The contents of %s' % testfile
msg['From'] = me
msg['To'] = you
# Send the message via our own SMTP server, but don't include the
# envelope header.
s = smtplib.SMTP('192.168.1.3')
s.sendmail(me, [you], msg.as_string())
s.quit()
the error is shown below:
File "x:\example.py", line 6, in SendTMail s = smtplib.SMTP('192.168.1.3')
File "x:\Python27\lib\smtplib.py", line 251, in init (code, msg) = self.connect(host, port)
File "x:\Python27\lib\smtplib.py", line 311, in connect self.sock = self._get_socket(host, port, self.timeout)
File "x:\Python27\lib\smtplib.py", line 286, in _get_socket return socket.create_connection((host, port), timeout)
File "x:\Python27\lib\socket.py", line 571, in create_connection raise err –
error: [Errno 10051] A socket operation was attempted to an unreachable network
Before posting raw code, I'd like to add an small explanation as per the conversation that took place in the comments to your question.
smtplib connects to an existing SMTP server. You can see it more like an Outlook Express. Outlook is a client (or a Mail User Agent, if you wanna get fancy). It doesn't send emails by itself. It connects to whatever SMTP server it has configured among its accounts and tells that server "Hey, I'm user xxx#hotmail.com (and here's my password to prove it). Could you send this for me?"
If you wanted to, having your own SMTP server is doable (for instance, in Linux, an easily configurable SMTP server would be Postfix, and I'm sure there are many for Windows) Once you set one up, it'll start listening for incoming connections in its port 25 (usually) and, if whatever bytes come through that port follow the SMTP protocol, it'll send it to its destination. IMHO, this isn't such a great idea (nowadays). The reason is that now, every (decent) email provider will consider emails coming from unverified SMTP servers as spam. If you want to send emails, is much better relying in a well known SMTP server (such as the one at smtp.live.com, the ones hotmail uses), authenticate against it with your username and password, and send your email relying (as in SMTP Relay) on it.
So this said, here's some code that sends an HTML text with an attachment borrajax.jpeg to an email account relying on smtp.live.com.
You'll need to edit the code below to set your hotmail's password (maybe your hotmail's username as well, if it's not 124#hotmail.co.uk as shown in your question) and email recipients. I removed mines from the code after my tests for obvious security reasons... for me :-D and I put back the ones I saw in your question. Also, this scripts assumes it'll find a .jpeg picture called borrajax.jpeg in the same directory where the Python script is being run:
import smtplib
from email.mime.image import MIMEImage
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
def send_mail():
test_str="This is a test"
me="124#hotmail.co.uk"
me_password="XXX" # Put YOUR hotmail password here
you="123#live.com"
msg = MIMEMultipart()
msg['Subject'] = test_str
msg['From'] = me
msg['To'] = you
msg.preamble = test_str
msg_txt = ("<html>"
"<head></head>"
"<body>"
"<h1>Yey!!</h1>"
"<p>%s</p>"
"</body>"
"</html>" % test_str)
msg.attach(MIMEText(msg_txt, 'html'))
with open("borrajax.jpeg") as f:
msg.attach(MIMEImage(f.read()))
smtp_conn = smtplib.SMTP("smtp.live.com", timeout=10)
print "connection stablished"
smtp_conn.starttls()
smtp_conn.ehlo_or_helo_if_needed()
smtp_conn.login(me, me_password)
smtp_conn.sendmail(me, you, msg.as_string())
smtp_conn.quit()
if __name__ == "__main__":
send_mail()
When I run the example (as I said, I edited the recipient and the sender) it sent an email to a Gmail account using my (old) hotmail account. This is what I received in my Gmail:
There's a lot of stuff you can do with the email Python module. Have fun!!
EDIT:
Gorramit!! Your comment about attaching a text file wouldn't let me relax!! :-D I had to see it myself. Following what was detailed in this question, I added some code to add a text file as an attachment.
msg_txt = ("<html>"
"<head></head>"
"<body>"
"<h1>Yey!!</h1>"
"<p>%s</p>"
"</body>"
"</html>" % test_str)
msg.attach(MIMEText(msg_txt, 'html'))
with open("borrajax.jpeg", "r") as f:
msg.attach(MIMEImage(f.read()))
#
# Start new stuff
#
with open("foo.txt", "r") as f:
txt_attachment = MIMEText(f.read())
txt_attachment.add_header('Content-Disposition',
'attachment',
filename=f.name)
msg.attach(txt_attachment)
#
# End new stuff
#
smtp_conn = smtplib.SMTP("smtp.live.com", timeout=10)
print "connection stablished"
And yep, it works... I have a foo.txt file in the same directory where the script is run and it sends it properly as an attachment.

How to send an email with Python?

This code works and sends me an email just fine:
import smtplib
#SERVER = "localhost"
FROM = 'monty#python.com'
TO = ["jon#mycompany.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('myserver')
server.sendmail(FROM, TO, message)
server.quit()
However if I try to wrap it in a function like this:
def sendMail(FROM,TO,SUBJECT,TEXT,SERVER):
import smtplib
"""this is some test documentation in the function"""
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()
and call it I get the following errors:
Traceback (most recent call last):
File "C:/Python31/mailtest1.py", line 8, in <module>
sendmail.sendMail(sender,recipients,subject,body,server)
File "C:/Python31\sendmail.py", line 13, in sendMail
server.sendmail(FROM, TO, message)
File "C:\Python31\lib\smtplib.py", line 720, in sendmail
self.rset()
File "C:\Python31\lib\smtplib.py", line 444, in rset
return self.docmd("rset")
File "C:\Python31\lib\smtplib.py", line 368, in docmd
return self.getreply()
File "C:\Python31\lib\smtplib.py", line 345, in getreply
raise SMTPServerDisconnected("Connection unexpectedly closed")
smtplib.SMTPServerDisconnected: Connection unexpectedly closed
Can anyone help me understand why?
I recommend that you use the standard packages email and smtplib together to send email. Please look at the following example (reproduced from the Python documentation). Notice that if you follow this approach, the "simple" task is indeed simple, and the more complex tasks (like attaching binary objects or sending plain/HTML multipart messages) are accomplished very rapidly.
# Import smtplib for the actual sending function
import smtplib
# Import the email modules we'll need
from email.mime.text import MIMEText
# Open a plain text file for reading. For this example, assume that
# the text file contains only ASCII characters.
with open(textfile, 'rb') as fp:
# Create a text/plain message
msg = MIMEText(fp.read())
# 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
# Send the message via our own SMTP server, but don't include the
# envelope header.
s = smtplib.SMTP('localhost')
s.sendmail(me, [you], msg.as_string())
s.quit()
For sending email to multiple destinations, you can also follow the example in the Python documentation:
# Import smtplib for the actual sending function
import smtplib
# Here are the email package modules we'll need
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
# Create the container (outer) email message.
msg = MIMEMultipart()
msg['Subject'] = 'Our family reunion'
# me == the sender's email address
# family = the list of all recipients' email addresses
msg['From'] = me
msg['To'] = ', '.join(family)
msg.preamble = 'Our family reunion'
# Assume we know that the image files are all in PNG format
for file in pngfiles:
# Open the files in binary mode. Let the MIMEImage class automatically
# guess the specific image type.
with open(file, 'rb') as fp:
img = MIMEImage(fp.read())
msg.attach(img)
# Send the email via our own SMTP server.
s = smtplib.SMTP('localhost')
s.sendmail(me, family, msg.as_string())
s.quit()
As you can see, the header To in the MIMEText object must be a string consisting of email addresses separated by commas. On the other hand, the second argument to the sendmail function must be a list of strings (each string is an email address).
So, if you have three email addresses: person1#example.com, person2#example.com, and person3#example.com, you can do as follows (obvious sections omitted):
to = ["person1#example.com", "person2#example.com", "person3#example.com"]
msg['To'] = ",".join(to)
s.sendmail(me, to, msg.as_string())
the ",".join(to) part makes a single string out of the list, separated by commas.
From your questions I gather that you have not gone through the Python tutorial - it is a MUST if you want to get anywhere in Python - the documentation is mostly excellent for the standard library.
When I need to mail in Python, I use the mailgun API which gets a lot of the headaches with sending mails sorted out. They have a wonderful app/api that allows you to send 5,000 free emails per month.
Sending an email would be like this:
def send_simple_message():
return requests.post(
"https://api.mailgun.net/v3/YOUR_DOMAIN_NAME/messages",
auth=("api", "YOUR_API_KEY"),
data={"from": "Excited User <mailgun#YOUR_DOMAIN_NAME>",
"to": ["bar#example.com", "YOU#YOUR_DOMAIN_NAME"],
"subject": "Hello",
"text": "Testing some Mailgun awesomness!"})
You can also track events and lots more, see the quickstart guide.
I'd like to help you with sending emails by advising the yagmail package (I'm the maintainer, sorry for the advertising, but I feel it can really help!).
The whole code for you would be:
import yagmail
yag = yagmail.SMTP(FROM, 'pass')
yag.send(TO, SUBJECT, TEXT)
Note that I provide defaults for all arguments, for example if you want to send to yourself, you can omit TO, if you don't want a subject, you can omit it also.
Furthermore, the goal is also to make it really easy to attach html code or images (and other files).
Where you put contents you can do something like:
contents = ['Body text, and here is an embedded image:', 'http://somedomain/image.png',
'You can also find an audio file attached.', '/local/path/song.mp3']
Wow, how easy it is to send attachments! This would take like 20 lines without yagmail ;)
Also, if you set it up once, you'll never have to enter the password again (and have it safely stored). In your case you can do something like:
import yagmail
yagmail.SMTP().send(contents = contents)
which is much more concise!
I'd invite you to have a look at the github or install it directly with pip install yagmail.
Here is an example on Python 3.x, much simpler than 2.x:
import smtplib
from email.message import EmailMessage
def send_mail(to_email, subject, message, server='smtp.example.cn',
from_email='xx#example.com'):
# import smtplib
msg = EmailMessage()
msg['Subject'] = subject
msg['From'] = from_email
msg['To'] = ', '.join(to_email)
msg.set_content(message)
print(msg)
server = smtplib.SMTP(server)
server.set_debuglevel(1)
server.login(from_email, 'password') # user & password
server.send_message(msg)
server.quit()
print('successfully sent the mail.')
call this function:
send_mail(to_email=['12345#qq.com', '12345#126.com'],
subject='hello', message='Your analysis has done!')
below may only for Chinese user:
If you use 126/163, 网易邮箱, you need to set"客户端授权密码", like below:
ref: https://stackoverflow.com/a/41470149/2803344
https://docs.python.org/3/library/email.examples.html#email-examples
There is indentation problem. The code below will work:
import textwrap
def sendMail(FROM,TO,SUBJECT,TEXT,SERVER):
import smtplib
"""this is some test documentation in the function"""
message = textwrap.dedent("""\
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()
While indenting your code in the function (which is ok), you did also indent the lines of the raw message string. But leading white space implies folding (concatenation) of the header lines, as described in sections 2.2.3 and 3.2.3 of RFC 2822 - Internet Message Format:
Each header field is logically a single line of characters comprising
the field name, the colon, and the field body. For convenience
however, and to deal with the 998/78 character limitations per line,
the field body portion of a header field can be split into a multiple
line representation; this is called "folding".
In the function form of your sendmail call, all lines are starting with white space and so are "unfolded" (concatenated) and you are trying to send
From: monty#python.com To: jon#mycompany.com Subject: Hello! This message was sent with Python's smtplib.
Other than our mind suggests, smtplib will not understand the To: and Subject: headers any longer, because these names are only recognized at the beginning of a line. Instead smtplib will assume a very long sender email address:
monty#python.com To: jon#mycompany.com Subject: Hello! This message was sent with Python's smtplib.
This won't work and so comes your Exception.
The solution is simple: Just preserve the message string as it was before. This can be done by a function (as Zeeshan suggested) or right away in the source code:
import smtplib
def sendMail(FROM,TO,SUBJECT,TEXT,SERVER):
"""this is some test documentation in the function"""
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()
Now the unfolding does not occur and you send
From: monty#python.com
To: jon#mycompany.com
Subject: Hello!
This message was sent with Python's smtplib.
which is what works and what was done by your old code.
Note that I was also preserving the empty line between headers and body to accommodate section 3.5 of the RFC (which is required) and put the include outside the function according to the Python style guide PEP-0008 (which is optional).
Make sure you have granted permission for both Sender and Receiver to send email and receive email from Unknown sources(External Sources) in Email Account.
import smtplib
#Ports 465 and 587 are intended for email client to email server communication - sending email
server = smtplib.SMTP('smtp.gmail.com', 587)
#starttls() is a way to take an existing insecure connection and upgrade it to a secure connection using SSL/TLS.
server.starttls()
#Next, log in to the server
server.login("#email", "#password")
msg = "Hello! This Message was sent by the help of Python"
#Send the mail
server.sendmail("#Sender", "#Reciever", msg)
It's probably putting tabs into your message. Print out message before you pass it to sendMail.
It's worth noting that the SMTP module supports the context manager so there is no need to manually call quit(), this will guarantee it is always called even if there is an exception.
with smtplib.SMTP_SSL('smtp.gmail.com', 465) as server:
server.ehlo()
server.login(user, password)
server.sendmail(from, to, body)
I haven't been satisfied with the package options for sending emails and I decided to make and open source my own email sender. It is easy to use and capable of advanced use cases.
To install:
pip install redmail
Usage:
from redmail import EmailSender
email = EmailSender(
host="<SMTP HOST ADDRESS>",
port=<PORT NUMBER>,
)
email.send(
sender="me#example.com",
receivers=["you#example.com"],
subject="An example email",
text="Hi, this is text body.",
html="<h1>Hi,</h1><p>this is HTML body</p>"
)
If your server requires a user and a password, just pass user_name and password to the EmailSender.
I have included a lot of features wrapped in the send method:
Include attachments
Include images directly to the HTML body
Jinja templating
Prettier HTML tables out of the box
Documentation:
https://red-mail.readthedocs.io/en/latest/
Source code: https://github.com/Miksus/red-mail
Thought I'd put in my two bits here since I have just figured out how this works.
It appears that you don't have the port specified on your SERVER connection settings, this effected me a little bit when I was trying to connect to my SMTP server that isn't using the default port: 25.
According to the smtplib.SMTP docs, your ehlo or helo request/response should automatically be taken care of, so you shouldn't have to worry about this (but might be something to confirm if all else fails).
Another thing to ask yourself is have you allowed SMTP connections on your SMTP server itself? For some sites like GMAIL and ZOHO you have to actually go in and activate the IMAP connections within the email account. Your mail server might not allow SMTP connections that don't come from 'localhost' perhaps? Something to look into.
The final thing is you might want to try and initiate the connection on TLS. Most servers now require this type of authentication.
You'll see I've jammed two TO fields into my email. The msg['TO'] and msg['FROM'] msg dictionary items allows the correct information to show up in the headers of the email itself, which one sees on the receiving end of the email in the To/From fields (you might even be able to add a Reply To field in here. The TO and FROM fields themselves are what the server requires. I know I've heard of some email servers rejecting emails if they don't have the proper email headers in place.
This is the code I've used, in a function, that works for me to email the content of a *.txt file using my local computer and a remote SMTP server (ZOHO as shown):
def emailResults(folder, filename):
# body of the message
doc = folder + filename + '.txt'
with open(doc, 'r') as readText:
msg = MIMEText(readText.read())
# headers
TO = 'to_user#domain.com'
msg['To'] = TO
FROM = 'from_user#domain.com'
msg['From'] = FROM
msg['Subject'] = 'email subject |' + filename
# SMTP
send = smtplib.SMTP('smtp.zoho.com', 587)
send.starttls()
send.login('from_user#domain.com', 'password')
send.sendmail(FROM, TO, msg.as_string())
send.quit()
Another implementation using gmail let's say:
import smtplib
def send_email(email_address: str, subject: str, body: str):
"""
send_email sends an email to the email address specified in the
argument.
Parameters
----------
email_address: email address of the recipient
subject: subject of the email
body: body of the email
"""
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login("email_address", "password")
server.sendmail("email_address", email_address,
"Subject: {}\n\n{}".format(subject, body))
server.quit()
I wrote a simple function send_email() for email sending with smtplib and email packages (link to my article). It additionally uses dotenv package to loads the sender email and password (please don't keep secrets in the code!). I was using Gmail for email service. The password was the App Password (here is Google docs on how to generate App Password).
import os
import smtplib
from email.message import EmailMessage
from dotenv import load_dotenv
_ = load_dotenv()
def send_email(to, subject, message):
try:
email_address = os.environ.get("EMAIL_ADDRESS")
email_password = os.environ.get("EMAIL_PASSWORD")
if email_address is None or email_password is None:
# no email address or password
# something is not configured properly
print("Did you set email address and password correctly?")
return False
# create email
msg = EmailMessage()
msg['Subject'] = subject
msg['From'] = email_address
msg['To'] = to
msg.set_content(message)
# send email
with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:
smtp.login(email_address, email_password)
smtp.send_message(msg)
return True
except Exception as e:
print("Problem during send email")
print(str(e))
return False
The above approach is OK for simple email sending. If you are looking for more advanced features, such as HTML content or attachments - it, of course, can be hand-coded, but I would recommend using existing packages, for example yagmail.
Gmail has a limit of 500 emails per day. For sending many emails per day please consider transactional email service providers, like Amazon SES, MailGun, MailJet, or SendGrid.
import smtplib
s = smtplib.SMTP(your smtp server, smtp port) #SMTP session
message = "Hii!!!"
s.sendmail("sender", "Receiver", message) # sending the mail
s.quit() # terminating the session
just to complement the answer and so that your mail delivery system can be scalable.
I recommend having a configuration file (it can be .json, .yml, .ini, etc) with the sender's email configuration , password and recipients.
This way you can create different customizable items according to your needs.
Below is a small example with 3 files, config, functions and main. Text-only mailing.
config_email.ini
[email_1]
sender = test#test.com
password = XXXXXXXXXXX
recipients= ["email_2#test.com", "email_2#test.com"]
[email_2]
sender = test_2#test.com
password = XXXXXXXXXXX
recipients= ["email_2#test.com", "email_2#test.com", "email_3#test.com"]
These items will be called from main.py, which will return their respective values.
File with functions functions_email.py:
import smtplib,configparser,json
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
def get_credentials(item):
parse = configparser.ConfigParser()
parse.read('config_email.ini')
sender = parse[item]['sender ']
password = parse[item]['password']
recipients= json.loads(parse[item]['recipients'])
return sender,password,recipients
def get_msg(sender,recipients,subject,mail_body):
msg = MIMEMultipart()
msg['Subject'] = subject
msg['From'] = sender
msg['To'] = ', '.join(recipients)
text = """\
"""+mail_body+""" """
part1 = MIMEText(text, "plain")
msg.attach(part1)
return msg
def send_email(msg,sender,password,recipients):
s = smtplib.SMTP('smtp.test.com')
s.login(sender,password)
s.sendmail(sender, recipients, msg.as_string())
s.quit()
File main.py:
from functions_email import *
sender,password,recipients = get_credenciales('email_2')
subject= 'text to subject'
mail_body = 'body....................'
msg = get_msg(sender,recipients ,subject,mail_body)
send_email(msg,sender,password,recipients)
Best regards!
import smtplib, ssl
port = 587 # For starttls
smtp_server = "smtp.office365.com"
sender_email = "170111018#student.mit.edu.tr"
receiver_email = "professordave#hotmail.com"
password = "12345678"
message = """\
Subject: Final exam
Teacher when is the final exam?"""
def SendMailf():
context = ssl.create_default_context()
with smtplib.SMTP(smtp_server, port) as server:
server.ehlo() # Can be omitted
server.starttls(context=context)
server.ehlo() # Can be omitted
server.login(sender_email, password)
server.sendmail(sender_email, receiver_email, message)
print("mail send")
After a lot of fiddling with the examples e.g here
this now works for me:
import smtplib
from email.mime.text import MIMEText
# SMTP sendmail server mail relay
host = 'mail.server.com'
port = 587 # starttls not SSL 465 e.g gmail, port 25 blocked by most ISPs & AWS
sender_email = 'name#server.com'
recipient_email = 'name#domain.com'
password = 'YourSMTPServerAuthenticationPass'
subject = "Server - "
body = "Message from server"
def sendemail(host, port, sender_email, recipient_email, password, subject, body):
try:
p1 = f'<p><HR><BR>{recipient_email}<BR>'
p2 = f'<h2><font color="green">{subject}</font></h2>'
p3 = f'<p>{body}'
p4 = f'<p>Kind Regards,<BR><BR>{sender_email}<BR><HR>'
message = MIMEText((p1+p2+p3+p4), 'html')
# servers may not accept non RFC 5321 / RFC 5322 / compliant TXT & HTML typos
message['From'] = f'Sender Name <{sender_email}>'
message['To'] = f'Receiver Name <{recipient_email}>'
message['Cc'] = f'Receiver2 Name <>'
message['Subject'] = f'{subject}'
msg = message.as_string()
server = smtplib.SMTP(host, port)
print("Connection Status: Connected")
server.set_debuglevel(1)
server.ehlo()
server.starttls()
server.ehlo()
server.login(sender_email, password)
print("Connection Status: Logged in")
server.sendmail(sender_email, recipient_email, msg)
print("Status: Email as HTML successfully sent")
except Exception as e:
print(e)
print("Error: unable to send email")
# Run
sendemail(host, port, sender_email, recipient_email, password, subject, body)
print("Status: Exit")
As far your code is concerned, there doesn't seem to be anything fundamentally wrong with it except that, it is unclear how you're actually calling that function. All I can think of is that when your server is not responding then you will get this SMTPServerDisconnected error. If you lookup the getreply() function in smtplib (excerpt below), you will get an idea.
def getreply(self):
"""Get a reply from the server.
Returns a tuple consisting of:
- server response code (e.g. '250', or such, if all goes well)
Note: returns -1 if it can't read response code.
- server response string corresponding to response code (multiline
responses are converted to a single, multiline string).
Raises SMTPServerDisconnected if end-of-file is reached.
"""
check an example at https://github.com/rreddy80/sendEmails/blob/master/sendEmailAttachments.py that also uses a function call to send an email, if that's what you're trying to do (DRY approach).

Categories