Script is working, i received zip file. But when i am trying to open zip file (WinRaR and 7-zip) i get error - archive is either in unknown format or damaged. Maybe problem related with encoding ???
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from email.mime.text import MIMEText
import smtplib
def send_mail():
sender = '*****#mail.ru'
password = '*************'
smtp_obj = smtplib.SMTP('smtp.mail.ru', 587)
smtp_obj.starttls()
msg = MIMEMultipart()
msg['Subject'] = 'Data from Experiment'
msg['From'] = sender
msg['To'] = sender
with open(r'C:\Users\Admin\Desktop\Python\Python + SQL\Send_email\arch\arch.zip',encoding='CP866') as file:
# Attach the file with filename to the email
msg.attach(MIMEApplication(file.read(), Name='arch.zip'))
# Login to the server
smtp_obj.login(sender, password)
# Convert the message to a string and send it
smtp_obj.sendmail(sender, sender, msg.as_string())
#smtp_obj.quit()
send_mail()
Do not pass an encoding when opening a zip file. That's binary data and should be treated as such! open(..., 'b')
Related
I am writing a script that would send me an email with updates. Two parts of the email are text that I want to read from the text file and send in the body and the png attachment.
The problem is that I receive an email with an image but there is no text. My text is quite large and contains \n, \t, and I guess that's the problem that I couldn't find a solution to.
Can you please advise me on how to efficiently add a bunch of text into the body of an email (not to the attachment)?
My code:
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from equity_plot import date_time
import smtplib
contacts = ['email']
msg = MIMEMultipart()
msg['Subject'] = 'Daily performance'
msg['From'] = 'email'
msg['To'] = ', '.join(contacts)
filename = 'text_doc.txt'
with open(filename, "r") as filename:
text = MIMEText(filename.read())
msg.attach(text)
attachment = f'Performance {date_time}.png'
with open(attachment, 'rb') as fp:
img = MIMEImage(fp.read())
msg.attach(img)
with smtplib.SMTP('server', port) as smtp:
smtp.ehlo()
smtp.starttls()
smtp.ehlo()
smtp.login('email', 'pass')
smtp.send_message(msg)
The goal is to send an email with excel attachment.
I found an example online but not written for Excel format.
It sends attachment but not like typical excel spreadsheet, so I am unable to open it.
Is it something I can modify in a code in order to receive .xlsx file?
# libraries to be imported
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
fromaddr = "From#gmail.com"
toaddr = "To#gmail.com"
# instance of MIMEMultipart
msg = MIMEMultipart()
# storing the senders email address
msg['From'] = fromaddr
# storing the receivers email address
msg['To'] = toaddr
# storing the subject
msg['Subject'] = "Sending Attachement"
# string to store the body of the mail
body = "Hello, This is Oleg and my attached file"
# attach the body with the msg instance
msg.attach(MIMEText(body, 'plain'))
# open the file to be sent
filename = "FileName"
attachment = open("C:\\Mylocation\\FileName.xlsx", "rb")
# instance of MIMEBase and named as p
p = MIMEBase('application', 'octet-stream')
# To change the payload into encoded form
p.set_payload((attachment).read())
# encode into base64
encoders.encode_base64(p)
p.add_header('Content-Disposition', "attachment; filename= %s" % filename)
# attach the instance 'p' to instance 'msg'
msg.attach(p)
# creates SMTP session
s = smtplib.SMTP('smtp.gmail.com', 587)
# start TLS for security
s.starttls()
# Authentication
s.login(fromaddr, "password")
# Converts the Multipart msg into a string
text = msg.as_string()
# sending the mail
s.sendmail(fromaddr, toaddr, text)
# terminating the session
s.quit()
There is just a small error in your code! change your filename variable to "FileName.xlsx" instead of just "FileName"
I noticed that your file didn't have an extension, and since your filename variable didn't have an extension - that is how I quickly came to this conclusion. The documentation for add_header() seems to use the file extensions as well.
I would like to create a text file in Python, write something to it, and then e-mail it out (put test.txt as an email attachment).
However, I cannot save this file locally. Does anyone know how to go about doing this?
As soon as I open the text file to write in, it is saved locally on my computer.
f = open("test.txt","w+")
I am using smtplib and MIMEMultipart to send the mail.
StringIO is the way to go...
from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from io import StringIO
email = MIMEMultipart()
email['Subject'] = 'subject'
email['To'] = 'recipient#example.com'
email['From'] = 'sender#example.com'
# Add the attachment to the message
f = StringIO()
# write some content to 'f'
f.write("content for 'test.txt'")
f.seek(0)
msg = MIMEBase('application', "octet-stream")
msg.set_payload(f.read())
encoders.encode_base64(msg)
msg.add_header('Content-Disposition',
'attachment',
filename='test.txt')
email.attach(msg)
I found this post while figuring out how to do this with the newer EmailMessage, which was introduced in Python 3.6 (see https://docs.python.org/3/library/email.message.html). It's slightly less code:
from email.message import EmailMessage
from io import StringIO
from smtplib import SMTP
message = EmailMessage()
message['Subject'] = 'Subject'
message['From'] = 'from#example.com'
message['To'] = 'to#example.com'
f = StringIO()
f.name = 'attachment.txt'
f.write('contents of file')
f.seek(0)
message.add_attachment(f.read(), filename=f.name)
with SMTP('yourmailserver.com', 25) as server:
server.send_message(message)
I am trying to send an email using the Python email client. I have written the following code but it sends the attachemnt as the body and not as an attached file.
Could someone please tell me what is wrong with the code:
# Import smtplib for the actual sending function
import smtplib
# Here are the email package modules we'll need
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
EMAIL_LIST = ['rec#rec.com']
# Create the container (outer) email message.
msg = MIMEMultipart()
msg['Subject'] = 'THIS DOES NOT WORK'
# me == the sender's email address
# family = the list of all recipients' email addresses
msg['From'] = 'send#sender.com'
print EMAIL_LIST
print '--------------------'
print ', '.join(EMAIL_LIST)
msg['To'] = ', '.join(EMAIL_LIST)
msg.preamble = 'THIS DOES NOT WORK'
fileName = 'c:\\p.trf'
with open(fileName, 'r') as fp:
attachment = MIMEText(fp.read())
fp.close()
msg.add_header('Content-Disposition', 'attachment', filename=fileName)
msg.attach(attachment)
# Send the email via our own SMTP server.
s = smtplib.SMTP('localhost')
s.sendmail('julka#pv.com', EMAIL_LIST, msg.as_string())
s.quit()
For the attachment, you should probably use, MIMEBase something like this:
import os
from email import encoders
from email.mime.base import MIMEBase
with open(fileName,'r') as fp:
attachment = MIMEBase('application','octet-stream')
attachment.set_payload(fp.read())
encoders.encode_base64(attachment)
attachment.add_header('Content-Disposition','attachment',filename=os.path.split(fileName)[1])
msg.attach(attachment)
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to send Email Attachments with python
I would like to edit the following code and send an email with an attachment. Attachment is a pdf file, it is under /home/myuser/sample.pdf, in linux environment. What should I change below?
import smtplib
fromaddr = 'myemail#gmail.com'
toaddrs = 'youremail#gmail.com'
msg = 'Hello'
# Credentials (if needed)
username = 'myemail'
password = 'yyyyyy'
# The actual mail send
server = smtplib.SMTP('smtp.gmail.com:587')
server.starttls()
server.login(username,password)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()
You create a message with an email package in this case -
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEImage import MIMEImage
msg = MIMEMultipart()
msg.attach(MIMEText(open("/home/myuser/sample.pdf").read()))
and then send the message.
import smtplib
mailer = smtplib.SMTP()
mailer.connect()
mailer.sendmail(from_, to, msg.as_string())
mailer.close()
Several examples here - http://docs.python.org/library/email-examples.html
UPDATE
Updating the link since the above yields a 404 https://docs.python.org/2/library/email-examples.html. Thanks #Tshirtman
Update2: Simplest way to attach pdf
To attach the pdf use the pdf flag:
def send_email_pdf_figs(path_to_pdf, subject, message, destination, password_path=None):
## credits: http://linuxcursor.com/python-programming/06-how-to-send-pdf-ppt-attachment-with-html-body-in-python-script
from socket import gethostname
#import email
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import smtplib
import json
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
with open(password_path) as f:
config = json.load(f)
server.login('me#gmail.com', config['password'])
# Craft message (obj)
msg = MIMEMultipart()
message = f'{message}\nSend from Hostname: {gethostname()}'
msg['Subject'] = subject
msg['From'] = 'me#gmail.com'
msg['To'] = destination
# Insert the text to the msg going by e-mail
msg.attach(MIMEText(message, "plain"))
# Attach the pdf to the msg going by e-mail
with open(path_to_pdf, "rb") as f:
#attach = email.mime.application.MIMEApplication(f.read(),_subtype="pdf")
attach = MIMEApplication(f.read(),_subtype="pdf")
attach.add_header('Content-Disposition','attachment',filename=str(path_to_pdf))
msg.attach(attach)
# send msg
server.send_message(msg)
inspirations/credits to: http://linuxcursor.com/python-programming/06-how-to-send-pdf-ppt-attachment-with-html-body-in-python-script
The recommended way is using Python's email module in order to compose a properly
formatted MIME messages. See docs
For python 2
https://docs.python.org/2/library/email-examples.html
For python 3
https://docs.python.org/3/library/email.examples.html