I am using Python to send a simple HTML email and have the basic code:
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.application import MIMEApplication
def send_test_mail(body):
sender_email = <SenderEmail>
receiver_email = <ReceiverEmail>
msg = MIMEMultipart()
msg['Subject'] = '[Email Test]'
msg['From'] = sender_email
msg['To'] = receiver_email
msgText = MIMEText('<b>%s</b>' % (body), 'html')
msg.attach(msgText)
try:
with smtplib.SMTP_SSL('smtp.gmail.com', 587) as smtpObj:
smtpObj.ehlo()
smtpObj.login(<LoginUserName>, <LoginPassword>)
smtpObj.sendmail(sender_email, receiver_email, msg.as_string())
except Exception as e:
print(e)
if __name__ == "__main__":
send_test_mail("Welcome to Medium!")
This has been put together from a couple of sources from within the stackexchange community but the intention is only to send a straightforward email.
But, when it is received, I get the paperclip icon indicating there is an attachment when there clearly isn't one.
https://i.stack.imgur.com/Ysj3g.png
Python is not my strong point but I'm sure it has more to do with SMTPLIB rather than python.
Does anyone know what is going on here?
Thanks
Related
I am geeting an error while I am trying to send an automated email from python.
The error I am getting is "[Errno 97] Address family not supported by protocol"
# import necessary packages
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import smtplib
# create message object instance
msg = MIMEMultipart()
password = "password"
msg['From'] = "risk#gmail.com"
msg['To'] = "game#gmail.com"
msg['Subject'] = "Photos"
# attach image to message body
server = smtplib.SMTP('smtp.gmail.com: 587')
server.starttls()
# Login Credentials for sending the mail
server.login(msg['From'], password)
server.sendmail(msg['From'], msg['To'], msg.as_string())
How can I fix this problem. Any help is appreciated.
I'm unsure if you have resolved this problem, so I'm posting the code that worked for me.
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
from email.mime.text import MIMEText
import smtplib
msg = MIMEMultipart()
password = "password"
msg['From'] = "risk#gmail.com"
msg['To'] = "game#gmail.com"
msg['Subject'] = "Photos"
text = "Here are the photos.\nCheers,\nLife is complex"
msg_text = MIMEText(text, 'plain')
msg.attach (msg_text)
fp = open('image.png', 'rb')
img = MIMEImage(fp.read())
fp.close()
msg.attach(img)
server = smtplib.SMTP('smtp.gmail.com: 587')
server.starttls()
# Login Credentials for sending the mail
server.login(msg['From'], password)
server.sendmail(msg['From'], msg['To'], msg.as_string())
BTW have you enabled the Gmail security setting that allows "less
secure application access' to your Gmail account? This setting allows
your python script to interact with your account.
I have an automated messaging system that sends emails with the three standard parameters, those being: To, destination and subject. The message is immediately sent after an error has been detected.
The message is being sent over Python, it receives the HTML-body from the monitoring system, it's NOT in the script itself. However, after I used mail-tester it came to light that I was missing the 'to' and 'date' header. However, I can't seem to find a way to add either of these two. I did some research and found out that there you can add mail options but can't find any parameters for this.
I also intend to send a plain-text only copy.
If there isn't an answer to this problem, what code should I try next to try and nail it down, PHP?
#!/usr/bin/env python
list1=[0, 1, 2, 3, 4];
import mimetypes, os, smtplib, sys
from email import encoders
from email.mime.audio import MIMEAudio
from email.mime.base import MIMEBase
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import formatdate
FROM='x#xx.com'
SRVSMTP='mysmtpserver:587'
DESTINATION=sys.argv[1]
SUBJECT=sys.argv[2]
MESSAGE=sys.argv[3]
PASS='xxxxxx'
msg = MIMEMultipart()
msg['From'] = FROM
msg['Subject'] = SUBJECT
msg['To'] = DESTINATION
msg['Date'] = formatdate()
msg.attach(MIMEText(MESSAGE, 'html', 'utf-8'))
raw = msg.as_string()
smtpserver = smtplib.SMTP(SRVSMTP)
smtpserver.ehlo()
smtpserver.starttls()
smtpserver.ehlo()
smtpserver.login(FROM, PASS)
smtpserver.sendmail(FROM, DESTINATION , raw)
I'm trying send an attachment with an e-mail using following code. But it gives an error. Without the attachment it works perfectly. What is the problem with this code?
"mail5.py", line 14
smtpObj = smtplib.SMTP('domain', 25)
^
SyntaxError: invalid syntax
#!/usr/bin/python
import smtplib
sender = 'a#a.com'
receivers = ['b#b.com']
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEImage import MIMEImage
msg = MIMEMultipart()
msg.attach(MIMEText(file("text.txt").read())
smtpObj = smtplib.SMTP('domain', 25)
smtpObj.sendmail(sender, receivers, msg.as_string())
print "Successfully sent email"
It looks like you're missing a closing parenthesis on the preceding line, try this:
msg.attach(MIMEText(file("text.txt").read()))
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