I am trying to send screenshots along with an email message..
The message gets through fine.
In Windows Live mail it has the attachment icon. but no attachments are there.
Online in outlook it has no attachment..
msg = MIMEMultipart('alternative')
msg['Subject'] = client_name + " eBay Template " + date
msg['From'] = sender_address
msg['To'] = recipients_address
msg.preamble = 'images'
...
# attach screenshot
iways_filename = dictstr['ItemID'] + "_i-ways" + '.png'
ebay_filename = dictstr['ItemID'] + "_ebay" + '.png'
# iways
img_data = open(iways_filename, 'rb').read()
image = MIMEImage(img_data, name=os.path.basename(iways_filename))
msg.attach(image)
#ebay
img_data2 = open(ebay_filename, 'rb').read()
image = MIMEImage(img_data2, name=os.path.basename(ebay_filename))
msg.attach(image)
I get no errors..
I found the solution..
msg = MIMEMultipart('alternative')
msg['Subject'] = client_name + " eBay Template " + date
msg['From'] = sender_address
msg['To'] = recipients_address
msg.preamble = 'images'
Take away the 'alternative' and Voila!
msg = MIMEMultipart()
msg['Subject'] = client_name + " eBay Template " + date
msg['From'] = sender_address
msg['To'] = recipients_address
msg.preamble = 'images'
Related
I'm wondering which approach is better for sending mail with different body using Python:
send each mail using separate functions
using one function and select body message with if-else statement
First case:
FROM = *from_email_address*
def send_mail_notify():
SUBJECT = *some_subject_for_notification_event*
TEXT = *any_text*
msg = EmailMessage()
msg['From'] = FROM
msg['To'] = *to_email_address*
msg['Subject'] = SUBJECT
msg.set_content(TEXT)
...(initialize connection to mail server, etc.)
FROM = *from_email_address*
def send_mail_error():
SUBJECT = *some_subject_for_error_event*
TEXT = *any_text*
msg = EmailMessage()
msg['From'] = FROM
msg['To'] = *email_address*
msg['Subject'] = SUBJECT
msg.set_content(TEXT)
...(initialize connection to mail server, etc.)
Second case:
FROM = *from_email_address*
def send_mail(param):
if param == "notify":
SUBJECT = *some_subject_for_notification_event*
TEXT = *any_text*
elif param == "error":
SUBJECT = *some_subject_for_error_event*
TEXT = *any_text*
msg = EmailMessage()
msg['From'] = FROM
msg['To'] = *email_address*
msg['Subject'] = SUBJECT
msg.set_content(TEXT)
...(initialize connection to mail server, etc.)
You can create an unlimited functions for different types of subject and text and you don't need to check the condition with if-else statement:
FROM = *from_email_address*
def notify():
return {"SUBJECT":"notification", "TEXT": "new message"}
def error():
return {"SUBJECT":"error: message dont send", "TEXT": "error message text"}
def send_mail(param):
msg = EmailMessage()
msg['From'] = FROM
msg['To'] = *email_address *
msg['Subject'] = globals().get(param)()["SUBJECT"]
msg.set_content(globals().get(param)()["TEXT"])
The param value must be the same as the name of the function.
I can't get this to attach multiple documents to an email. It attaches the first document and then sends the document. I am a noob when it comes to using the auto-email function. Could anyone explain this or show me how to fix this?
self.name = name
fromaddr = "Your Email"
toaddr = "Sending Email"
msg = MIMEMultipart()
#email address
msg['From'] = fromaddr
# Receivers email address
msg['To'] = toaddr
#subject
msg['Subject'] = ' Weekly Report'
#body of the mail
body = 'Hey, I\'m testing the automated email function, let me know if you get it and how does it look!'
#msg instance
msg.attach(MIMEText(body, 'plain'))
# open the file to be sent
a = 0
for i in self.name:
while a < len(self.name):
filename = i + '.pdf'
attachment = open(i + '.pdf', "rb")
a+=1
print(len(self.name))
print(a)
p = MIMEBase('application', 'octet-stream')
p.set_payload((attachment).read())
encoders.encode_base64(p)
p.add_header('Content-Disposition', "attachment; filename= %s" % filename)
msg.attach(p)
s = smtplib.SMTP('smtp.gmail.com', 587)
s.starttls()
s.login(fromaddr, "password")
text = msg.as_string()
s.sendmail(fromaddr, toaddr, text)
s.quit()
Try this (Reference:- https://dzone.com/articles/send-email-attachments-python)
import smtplib
import os
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email.Utils import COMMASPACE, formatdate
from email import Encoders
def send_mail(send_from, send_to, subject, text, files=[], server="localhost"):
assert type(send_to)==list
assert type(files)==list
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(file,"rb").read() )
Encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f))
msg.attach(part)
smtp = smtplib.SMTP(server)
smtp.sendmail(send_from, send_to, msg.as_string())
smtp.close()
I have a code which sends an email that uses HTML for templating.
All of the recipients get the message, but all of them are BCC.
def sendMail(to, cc, bcc, template, bodyParams, subjectParams):
global connection
if not testCurrentConnection(connection):
connect(currentConnectionName)
msg = MIMEMultipart('alternative')
subject, fromEmail, body = templateController.readTemplate(template)
header = 'To: ' + to + '\n' + 'Cc: ' + cc + 'From: ' + fromEmail + '\n' + 'Subject: ' + subject + '\n'
msg.attach(MIMEText(header, 'text'))
if subjectParams:
msg['Subject'] = templateController.replaceTextWithParams(subject, subjectParams)
else:
msg['Subject'] = subject
if bodyParams:
msg['Body'] = templateController.replaceTextWithParams(body, bodyParams)
else:
msg['Body'] = body
msg['From'] = fromEmail
msg['To'] = to
msg['Cc'] = cc
# no need to specify bcc here
msg.attach(MIMEText(msg['Body'], 'html'))
connection.sendmail(msg['From'], [msg['To'], msg['Cc'], bcc], msg.as_string())
del msg
I'm calling the function like this:
smtpController.sendMail("myMail#gmail.com", "ccMail#gmail.com", "", "email.html", None, None)
(The last two variables are actually a dict with key-value mapping used to populate the HTML, but the problem reproduces without them)
I read that I need to add header to my message to prevent it but for some reason, adding the header doesn't change anything (lines 7-8 in the above code).
What am I missing?
OK, I don't know how it makes a difference, but I fixed it by moving msg['To'] = to and msg['Cc'] = cc up, before Subject and Body. I completely removed the header.
def sendMail(to, cc, bcc, template, bodyParams, subjectParams):
global connection
if not testCurrentConnection(connection):
connect(currentConnectionName)
subject, fromEmail, body = templateController.readTemplate(template)
msg = MIMEMultipart('alternative')
msg['From'] = fromEmail
msg['To'] = to
msg['Cc'] = cc
if subjectParams:
msg['Subject'] = templateController.replaceTextWithParams(subject, subjectParams)
else:
msg['Subject'] = subject
if bodyParams:
msg['Body'] = templateController.replaceTextWithParams(body, bodyParams)
else:
msg['Body'] = body
msg.attach(MIMEText(msg['Body'], 'html'))
connection.sendmail(msg['From'], to.split(',') + cc.split(',') + bcc.split(','), msg.as_string())
del msg
I am sending email with my raspberrypi with python.
I successfully sent and received the message, but the content is missing.
Here is my code
import smtplib
smtpUser = 'myemail#gmail.com'
smtpPass = 'mypassword'
toAdd = 'target#gmail.com'
fromAdd = smtpUser
subject = 'Python Test'
header = 'To: ' + toAdd + '\n' + 'From: ' + fromAdd + '\n' + 'Subject: ' + subject
body = 'From within a Python script'
msg = header + '\n' + body
print header + '\n' + body
s = smtplib.SMTP('smtp.gmail.com',587)
s.ehlo()
s.starttls()
s.ehlo()
s.login(smtpUser,smtpPass)
s.sendmail(fromAdd, toAdd, msg)
s.quit()
Thank you for your attention!
I wrote a wrapper around sending emails in python; it makes sending emails super easy: https://github.com/krystofl/krystof-utils/blob/master/python/krystof_email_wrapper.py
Use it like so:
emailer = Krystof_email_wrapper()
email_body = 'Hello, <br /><br />' \
'This is the body of the email.'
emailer.create_email('sender#example.com', 'Sender Name',
['recipient#example.com'],
email_body,
'Email subject!',
attachments = ['filename.txt'])
cred = { 'email': 'sender#example.com', 'password': 'VERYSECURE' }
emailer.send_email(login_dict = cred, force_send = True)
You can also look at the source code to find how it works.
The relevant bits:
import email
import smtplib # sending of the emails
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
self.msg = MIMEMultipart()
self.msg.preamble = "This is a multi-part message in MIME format."
# set the sender
author = email.utils.formataddr((from_name, from_email))
self.msg['From'] = author
# set recipients (from list of email address strings)
self.msg['To' ] = ', '.join(to_emails)
self.msg['Cc' ] = ', '.join(cc_emails)
self.msg['Bcc'] = ', '.join(bcc_emails)
# set the subject
self.msg['Subject'] = subject
# set the body
msg_text = MIMEText(body.encode('utf-8'), 'html', _charset='utf-8')
self.msg.attach(msg_text)
# send the email
session = smtplib.SMTP('smtp.gmail.com', 587)
session.ehlo()
session.starttls()
session.login(login_dict['email'], login_dict['password'])
session.send_message(self.msg)
session.quit()
I want to resend email with attachments in Python. I have this code for sending email but how can I reference to attachment in another email?
Sending
def show_emails():
M.select()
typ, data = M.search(None, 'All')
for num in data[0].split():
typ, data = M.fetch(num, '(RFC822)')
parser = Parser()
email = parser.parsestr(data[0][1])
print "MESSAGE NUMBER %s" % (num)
print 'Raw Date:'
print email.get('Date')
print "From:"
print email.get('From')
print "Subject: "
print email.get('Subject')
And this code is for sending
msg = MIMEMultipart()
mfrom = 'from#abc.com'
mto = 'to#abc.com'
msg['Subject'] = 'test'
msg['From'] = mfrom
msg['To'] = mto
msg['Date'] = formatdate()
# Open the file to scan in binary mode
fp = open('/path/to/file', 'rb')
attachment = MIMEBase('application', 'octet-stream')
attachment.set_payload(fp.read())
encoders.encode_base64(attachment)
attachment.add_header('Content-Disposition', 'attachment; filename="filename"')
fp.close()
msg.attach(attachment)
I know I need to check if there is any attachment. And how can I reference to attachment and forward it?
if msg.is_multipart():
for part in msg.walk():
fileName = part.get_filename()
if bool(fileName):
print "Attachment: %s " % (decode_header(fileName)[0][0])
else:
print "No attachments"
You cannot just reference it: that's what RFCs 4467-9 were for, but those weren't implemented by many servers and at this point I think they're dead. You have to download the attachment and send it as if you were sending a local file.