I HAVE A LITTLE PROBLEM.
I USE:
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()
AND EVERTHING IS OKAY - BUT I WOULD LIKE TO ADD A TXT FILE ATTACHMENT. CAN YOU HELP ME?
You could achieve it like this:
filename = ...
with open(filename,'r') as f:
message = MIMEText(f.read())
message.add_header('Content-Disposition', 'attachment', filename=filename)
msg.attach(message)
where msg is the MIMEMultiPart object.
I FIND ANSWER TO BUT THANKS A LOT ! :)
filename='/www/pages/DANE/komunikaty.txt'
fp=open(filename,'rb')
att = email.mime.application.MIMEApplication(fp.read(),_subtype="txt")
fp.close()
att.add_header('Content-Disposition','attachment',filename=filename)
msg.attach(att)
Related
How can I attach some files to an MIME multipart email using Python3?
I want to send some attachments as "downloadable content" to my HTML-mail (with a plain text fallback). Couldn't find anything so far...
Edit: After a few trys I just made it to send my file. Thanks for the tip #tripleee. But unfortunatly my HTML is now sent as plain text...
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.utils import formatdate
from os.path import basename
import smtplib
login = "*********"
password = "*********"
server = "smail.*********:25"
files = ['Anhang/file.png']
# Create the root message and fill in the from, to, and subject headers
msg = MIMEMultipart('related')
msg['From'] = "*********"
msg['To'] = "*********"
msg['Date'] = formatdate(localtime=True)
msg['Subject'] = "*********"
msg['Reply-To'] = "*********"
msg.preamble = 'This is a multi-part message in MIME format.'
# Encapsulate the plain and HTML versions of the message body in an
# 'alternative' part, so message agents can decide which they want to display.
msgAlternative = MIMEMultipart('alternative')
with open('*********.txt', 'r') as plainTXT:
plain = plainTXT.read()
plainTXT.close()
msgAlternative.attach(MIMEText(plain))
with open('*********.html', 'r') as plainHTML:
html = plainHTML.read()
plainHTML.close()
msgAlternative.attach(MIMEText(html))
msg.attach(msgAlternative)
# Image
for f in files or []:
with open(f, "rb") as fp:
part = MIMEImage(
fp.read(),
Name=basename(f)
)
# closing file
part['Content-Disposition'] = 'attachment; filename="%s"' % basename(f)
msg.attach(part)
# create server
server = smtplib.SMTP(server)
server.starttls()
# Login Credentials for sending the mail
server.login(login, password)
# send the message via the server.
server.sendmail(msg['From'], msg['To'], msg.as_string())
server.quit()
print("successfully sent email to %s:" % (msg['To']));
I just had to use MIMEText(html, 'html') for the attaching part of my HTML.
Working code:
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.utils import formatdate
from os.path import basename
import smtplib
login = "YourLogin"
password = "YourPassword"
server = "SMTP-Server:Port"
files = ['files']
# Create the root message and fill in the from, to, and subject headers
msg = MIMEMultipart('related')
msg['From'] = "FromEmail"
msg['To'] = "ToEmail"
msg['Date'] = formatdate(localtime=True)
msg['Subject'] = "EmailSubject"
msg['Reply-To'] = "EmailReply"
msg.preamble = 'This is a multi-part message in MIME format.'
# Encapsulate the plain and HTML versions of the message body in an
# 'alternative' part, so message agents can decide which they want to display.
msgAlternative = MIMEMultipart('alternative')
with open('YourPlaintext.txt', 'r') as plainTXT:
plain = plainTXT.read()
plainTXT.close()
msgAlternative.attach(MIMEText(plain, 'plain'))
with open('YourHTML.html', 'r') as plainHTML:
html = plainHTML.read()
plainHTML.close()
msgAlternative.attach(MIMEText(html, 'html'))
msg.attach(msgAlternative)
# Image
for f in files or []:
with open(f, "rb") as fp:
part = MIMEImage(
fp.read(),
Name=basename(f)
)
# closing file
part['Content-Disposition'] = 'attachment; filename="%s"' % basename(f)
msg.attach(part)
# create server
server = smtplib.SMTP(server)
server.starttls()
# Login Credentials for sending the mail
server.login(login, password)
# send the message via the server.
server.sendmail(msg['From'], msg['To'], msg.as_string())
server.quit()
print("successfully sent email to %s:" % (msg['To']));
Thanks to #tripleee
I have written a python script to send email from my gmail account to my another email. the code is:
import smtplib
fromaddr = 'my#gmail.com'
toaddrs = 'to#gmail.com'
msg = 'my message'
username = 'my#gmail.com'
password = 'myPass'
server = smtplib.SMTP('smtp.gmail.com:587')
server.ehlo()
server.starttls()
server.login(username,password)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()
print("Done")
I'm also getting the "Done" output as the email is being sent. But the problem is: I can't seem to receive the email. It doesn't show up in the inbox. I can't find the problem :( Can anyone please help?
Thanks in advance...
Check this out, this works for me perfectly...
def send_mail(self):
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
gmailUser = 'myemail#gmail.com'
gmailPassword = 'P#ssw0rd'
recipient = 'sendto#gmail.com'
message='your message here '
msg = MIMEMultipart()
msg['From'] = gmailUser
msg['To'] = recipient
msg['Subject'] = "Subject of the email"
msg.attach(MIMEText(message))
mailServer = smtplib.SMTP('smtp.gmail.com', 587)
mailServer.ehlo()
mailServer.starttls()
mailServer.ehlo()
mailServer.login(gmailUser, gmailPassword)
mailServer.sendmail(gmailUser, recipient, msg.as_string())
mailServer.close()
Enable less secure apps on your gmail account and for Python3 use:
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
gmailUser = 'XXXXX#gmail.com'
gmailPassword = 'XXXXX'
recipient = 'XXXXX#gmail.com'
message = f"""
Your message here...
"""
msg = MIMEMultipart()
msg['From'] = f'"Your Name" <{gmailUser}>'
msg['To'] = recipient
msg['Subject'] = "Your Subject..."
msg.attach(MIMEText(message))
try:
mailServer = smtplib.SMTP('smtp.gmail.com', 587)
mailServer.ehlo()
mailServer.starttls()
mailServer.ehlo()
mailServer.login(gmailUser, gmailPassword)
mailServer.sendmail(gmailUser, recipient, msg.as_string())
mailServer.close()
print ('Email sent!')
except:
print ('Something went wrong...')
How do i add a document attachment when sending an email with python ?
i get the email to send
(please ignore: i am looping the email to send every 5 seconds, only for testing purposes, i want it to send every 30 min, just have to change 5 to 1800)
here is my code so far. how do i attach a document from my computer?
#!/usr/bin/python
import time
import smtplib
while True:
TO = 'xxxx#gmail.com'
SUBJECT = 'Python Email'
TEXT = 'Here is the message'
gmail_sender = 'xxxx#gmail.com'
gmail_passwd = 'xxxx'
server = smtplib.SMTP('smtp.gmail.com',587)
server.ehlo()
server.starttls()
server.ehlo()
server.login(gmail_sender, gmail_passwd)
BODY = '\n'.join([
'To: %s' % TO,
'From: %s' % gmail_sender,
'Subject:%s' % SUBJECT,
'',
TEXT
])
try:
server.sendmail(gmail_sender,[TO], BODY)
print 'email sent'
except:
print 'error sending mail'
time.sleep(5)
server.quit()
This is the code that worked for me- to send an email with an attachment in python
#!/usr/bin/python
import smtplib,ssl
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email.utils import formatdate
from email import encoders
def send_mail(send_from,send_to,subject,text,files,server,port,username='',password='',isTls=True):
msg = MIMEMultipart()
msg['From'] = send_from
msg['To'] = send_to
msg['Date'] = formatdate(localtime = True)
msg['Subject'] = subject
msg.attach(MIMEText(text))
part = MIMEBase('application', "octet-stream")
part.set_payload(open("WorkBook3.xlsx", "rb").read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="WorkBook3.xlsx"')
msg.attach(part)
#context = ssl.SSLContext(ssl.PROTOCOL_SSLv3)
#SSL connection only working on Python 3+
smtp = smtplib.SMTP(server, port)
if isTls:
smtp.starttls()
smtp.login(username,password)
smtp.sendmail(send_from, send_to, msg.as_string())
smtp.quit()
I found an easy way to do it using what Corey Shafer explains in this video on sending emails with python.
import smtplib
from email.message import EmailMessage
SENDER_EMAIL = "sender_email#gmail.com"
APP_PASSWORD = "xxxxxxx"
def send_mail_with_excel(recipient_email, subject, content, excel_file):
msg = EmailMessage()
msg['Subject'] = subject
msg['From'] = SENDER_EMAIL
msg['To'] = recipient_email
msg.set_content(content)
with open(excel_file, 'rb') as f:
file_data = f.read()
msg.add_attachment(file_data, maintype="application", subtype="xlsx", filename=excel_file)
with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:
smtp.login(SENDER_EMAIL, APP_PASSWORD)
smtp.send_message(msg)
Here is just a slight tweak on SoccerPlayer's post above that got me 99% of the way there. I found a snippet Here that got me the rest of the way. No credit is due to me. Just posting in case it helps the next person.
file = 'File.xlsx'
username=''
password=''
send_from = ''
send_to = 'recipient1 , recipient2'
Cc = 'recipient'
msg = MIMEMultipart()
msg['From'] = send_from
msg['To'] = send_to
msg['Cc'] = Cc
msg['Date'] = formatdate(localtime = True)
msg['Subject'] = ''
server = smtplib.SMTP('smtp.gmail.com')
port = '587'
fp = open(file, 'rb')
part = MIMEBase('application','vnd.ms-excel')
part.set_payload(fp.read())
fp.close()
encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment', filename='Name File Here')
msg.attach(part)
smtp = smtplib.SMTP('smtp.gmail.com')
smtp.ehlo()
smtp.starttls()
smtp.login(username,password)
smtp.sendmail(send_from, send_to.split(',') + msg['Cc'].split(','), msg.as_string())
smtp.quit()
Using python 3, you can use MIMEApplication:
import os, smtplib, traceback
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
def sendMail(sender,
subject,
recipient,
username,
password,
message=None,
xlsx_files=None):
msg = MIMEMultipart()
msg["Subject"] = subject
msg["From"] = sender
if type(recipient) == list:
msg["To"] = ", ".join(recipient)
else:
msg["To"] = recipient
message_text = MIMEText(message, 'html')
msg.attach(message_text)
if xlsx_files:
for f in xlsx_files:
attachment = open(f, 'rb')
file_name = os.path.basename(f)
part = MIMEApplication(attachment.read(), _subtype='xlsx')
part.add_header('Content-Disposition', 'attachment', filename=file_name)
msg.attach(part)
try:
server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
server.ehlo()
server.login(username, password)
server.sendmail(sender, recipient, msg.as_string())
server.close()
except Exception as e:
error = traceback.format_exc()
print(error)
print(e)
Note* I simply used print(error) in this example. Typically, I send errors to logging.critical(error)
To send an attachment create a MIMEMultipart object and add the attachment to that. Here is an example from the python email examples.
# 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
COMMASPACE = ', '
# 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'] = COMMASPACE.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.
fp = open(file, 'rb')
img = MIMEImage(fp.read())
fp.close()
msg.attach(img)
# Send the email via our own SMTP server.
s = smtplib.SMTP('localhost')
s.sendmail(me, family, msg.as_string())
s.quit()
You can also accomplish this with Red Mail nicely:
from redmail import EmailSender
from pathlib import Path
import pandas as pd
gmail = EmailSender(
host='smtp.gmail.com',
port=465,
user_name="you#gmail.com",
password="<YOUR PASSWORD>"
)
gmail.send(
subject="Python Email",
receivers=["you#gmail.com"],
text="Here is the message",
attachments={
# From path on disk
"my_file.xlsx": Path("path/to/file.xlsx"),
# Or from Pandas dataframe
"my_frame.xlsx": pd.DataFrame({"a": [1,2,3]})
}
)
You may also pass bytes if you wish to attach your Excel file that way.
To install Red Mail:
pip install redmail
Red Mail is an open source email library full of features. It is well tested and well documented. Documentation is found here: https://red-mail.readthedocs.io/en/latest/
I am sending a plain text email as follows:
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
def send_message():
msg = MIMEMultipart('alternative')
s = smtplib.SMTP('smtp.sendgrid.net', 587)
s.login(USERNAME, PASSWORD)
toEmail, fromEmail = to#email.com, from#email.com
msg['Subject'] = 'subject'
msg['From'] = fromEmail
body = 'This is the message'
content = MIMEText(body, 'plain')
msg.attach(content)
s.sendmail(fromEmail, toEmail, msg.as_string())
In addition to this message, I would like to attach a txt file, 'log_file.txt'. How would I attach a txt file here?
The same way, using msg.attach:
from email.mime.text import MIMEText
filename = "text.txt"
f = file(filename)
attachment = MIMEText(f.read())
attachment.add_header('Content-Disposition', 'attachment', filename=filename)
msg.attach(attachment)
Since Python3.6, I would recommend start using EmailMessage instead of MimeMultipart. Fewer imports, fewer lines, no need to put the recipients both to the message headers and to the SMTP sender function parameter.
import smtplib
from email.message import EmailMessage
msg = EmailMessage()
msg["From"] = FROM_EMAIL
msg["Subject"] = "Subject"
msg["To"] = TO_EMAIL
msg.set_content("This is the message body")
msg.add_attachment(open(filename, "r").read(), filename="log_file.txt")
s = smtplib.SMTP('smtp.sendgrid.net', 587)
s.login(USERNAME, PASSWORD)
s.send_message(msg)
Even better is to install library envelope by pip3 install envelope that's aim is to handle many things in a very intuitive manner:
from envelope import Envelope
from pathlib import Path
Envelope()\
.from_(FROM_EMAIL)\
.subject("Subject")\
.to("to")\
.message("message")\
.attach(Path(filename))\
.smtp("smtp.sendgrid.net", 587, USERNAME, PASSWORD)\
.send()
It works for me
sender = 'spider#fromdomain.com'
receivers = 'who'
msg = MIMEMultipart()
msg['Subject'] = 'subject'
msg['From'] = 'spider man'
msg['To'] = 'who#gmail.com'
file='myfile.xls'
msg.attach(MIMEText("Labour"))
attachment = MIMEBase('application', 'octet-stream')
attachment.set_payload(open(file, 'rb').read())
encoders.encode_base64(attachment)
attachment.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(file))
msg.attach(attachment)
print('Send email.')
conn.sendmail(sender, receivers, msg.as_string())
conn.close()
I am looking for a quick example on how to send Gmail emails with multiple CC:'s. Could anyone suggest an example snippet?
I've rustled up a bit of code for you that shows how to connect to an SMTP server, construct an email (with a couple of addresses in the Cc field), and send it. Hopefully the liberal application of comments will make it easy to understand.
from smtplib import SMTP_SSL
from email.mime.text import MIMEText
## The SMTP server details
smtp_server = "smtp.gmail.com"
smtp_port = 587
smtp_username = "username"
smtp_password = "password"
## The email details
from_address = "address1#domain.com"
to_address = "address2#domain.com"
cc_addresses = ["address3#domain.com", "address4#domain.com"]
msg_subject = "This is the subject of the email"
msg_body = """
This is some text for the email body.
"""
## Now we make the email
msg = MIMEText(msg_body) # Create a Message object with the body text
# Now add the headers
msg['Subject'] = msg_subject
msg['From'] = from_address
msg['To'] = to_address
msg['Cc'] = ', '.join(cc_addresses) # Comma separate multiple addresses
## Now we can connect to the server and send the email
s = SMTP_SSL(smtp_server, smtp_port) # Set up the connection to the SMTP server
try:
s.set_debuglevel(True) # It's nice to see what's going on
s.ehlo() # identify ourselves, prompting server for supported features
# If we can encrypt this session, do it
if s.has_extn('STARTTLS'):
s.starttls()
s.ehlo() # re-identify ourselves over TLS connection
s.login(smtp_username, smtp_password) # Login
# Send the email. Note we have to give sendmail() the message as a string
# rather than a message object, so we need to do msg.as_string()
s.sendmail(from_address, to_address, msg.as_string())
finally:
s.quit() # Close the connection
Here's the code above on pastie.org for easier reading
Regarding the specific question of multiple Cc addresses, as you can see in the code above, you need to use a comma separated string of email addresses, rather than a list.
If you want names as well as addresses you might as well use the email.utils.formataddr() function to help get them into the right format:
>>> from email.utils import formataddr
>>> addresses = [("John Doe", "john#domain.com"), ("Jane Doe", "jane#domain.com")]
>>> ', '.join([formataddr(address) for address in addresses])
'John Doe <john#domain.com>, Jane Doe <jane#domain.com>'
Hope this helps, let me know if you have any problems.
If you can use a library, I highly suggest http://libgmail.sourceforge.net/, I have used briefly in the past, and it is very easy to use. You must enable IMAP/POP3 in your gmail account in order to use this.
As for a code snippet (I haven't had a chance to try this, I will edit this if I can):
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email import Encoders
import os
#EDIT THE NEXT TWO LINES
gmail_user = "your_email#gmail.com"
gmail_pwd = "your_password"
def mail(to, subject, text, attach, cc):
msg = MIMEMultipart()
msg['From'] = gmail_user
msg['To'] = to
msg['Subject'] = subject
#THIS IS WHERE YOU PUT IN THE CC EMAILS
msg['Cc'] = cc
msg.attach(MIMEText(text))
part = MIMEBase('application', 'octet-stream')
part.set_payload(open(attach, 'rb').read())
Encoders.encode_base64(part)
part.add_header('Content-Disposition',
'attachment; filename="%s"' % os.path.basename(attach))
msg.attach(part)
mailServer = smtplib.SMTP("smtp.gmail.com", 587)
mailServer.ehlo()
mailServer.starttls()
mailServer.ehlo()
mailServer.login(gmail_user, gmail_pwd)
mailServer.sendmail(gmail_user, to, msg.as_string())
# Should be mailServer.quit(), but that crashes...
mailServer.close()
mail("some.person#some.address.com",
"Hello from python!",
"This is a email sent with python")
For the snippet I modified this