I am using Python smtp module sending mail, it's send success and looks good in outlook. By when I checking in mobile phone, it's no content but only attachment.Actually there are three tables in content. Is anyone know how to fix this issue? Below is my code.
def send_mail(subject, sender, recipient, cc, toaddrs, body, filename):
msg = MIMEMultipart('alternative')
msg['Subject'] = subject
msg['From'] = sender
msg['To'] = ", ".join(recipient)
msg['Cc'] = ", ".join(cc)
message = MIMEText(body, 'html') # html.read(), 'html')
msg.attach(message)
attachment = MIMEBase('application', 'octet-stream')
attachment.set_payload(open(filename, 'rb').read())
encoders.encode_base64(attachment)
attachment.add_header(
'Content-Disposition', 'attachment; filename="%s"' % os.path.basename(filename))
msg.attach(attachment)
smtp = smtplib.SMTP('localhost')
smtp.sendmail(sender, toaddrs, msg.as_string())
logger.info('Email have sent successfully!')
smtp.quit()
Any help will be appreciate.
Thanks.
Fix this by attachment and then attach message.
def send_mail(subject, sender, recipient, cc, toaddrs, body, filename):
msg = MIMEMultipart('alternative')
msg['Subject'] = subject
msg['From'] = sender
msg['To'] = ", ".join(recipient)
msg['Cc'] = ", ".join(cc)
attachment = MIMEBase('application', 'octet-stream')
attachment.set_payload(open(filename, 'rb').read())
encoders.encode_base64(attachment)
attachment.add_header(
'Content-Disposition', 'attachment; filename="%s"' % os.path.basename(filename))
msg.attach(attachment)
message = MIMEText(body, 'html') # html.read(), 'html')
msg.attach(message)
smtp = smtplib.SMTP('localhost')
smtp.sendmail(sender, toaddrs, msg.as_string())
logger.info('Email have sent successfully!')
smtp.quit()
Related
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()
The problem is in subject. That's ok when I do
import smtplib
s = smtplib.SMTP('smtp.gmail.com', 587)
s.starttls()
s.login(".....#gmail.com", "........")
message = u"бла бла бла".encode('utf8')
s.sendmail(".....#gmail.com", ".....#gmail.com", message)
But I get an error when I do
subject = u'бла бла бла'.encode('utf8')
body = u'бла бла бла'.encode('utf8')
email_text = """\
From: %s
To: %s
Subject: %s
%s
""" % (sent_from, ", ".join(to), subject, body)
try:
server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
server.ehlo()
server.login("......#gmail.com", ".......")
server.sendmail(sent_from, to, email_text)
s.quit()
print ('Email sent!')
except:
print ('Something went wrong...')
I add
from email.mime.text import MIMEText
subject = MIMEText('текст 1', 'plain')
body = MIMEText('текст 2', 'plain')
then again
try:
server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
server.ehlo()
server.login("......#gmail.com", ".......")
server.sendmail(sent_from, to, email_text)
s.quit()
print ('Email sent!')
except:
print ('Something went wrong...')
I get the letter but
in subject field
Content-Type: text/plain; charset="utf-8"
In body field
текст 1
i.e in body field I get text from subject. Ho to fix it?
Just to add
from email.header import Header
Subject= Header('бла бла бла', 'utf-8')
Sorry
This what worked for me
part.add_header('content-disposition', 'attachment', filename=('utf-8', '', ATTACHMENT_NAME))
Complete code sample for sending email with attachment:
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email import encoders
ATTACHMENT_NAME = 'отчет.xlsx'
def send_email():
msg = MIMEMultipart()
msg['Subject'] = EMAIL_SUBJECT
msg['From'] = USERNAME
msg['To'] = ", ".join(RECIPIENTS)
msg.attach(MIMEText(EMAIL_TEXT))
with open(REPORT_FILE, 'rb') as f:
part = MIMEBase('application', "octet-stream")
part.set_payload(f.read())
encoders.encode_base64(part)
part.add_header('content-disposition', 'attachment', filename=('utf-8', '', ATTACHMENT_NAME))
msg.attach(part)
s = smtplib.SMTP(SERVER)
s.login(USERNAME, PASSWORD)
s.sendmail(USERNAME, RECIPIENTS, msg.as_string())
s.quit()
So I have the following code for sending email with a zip attachment using smtplib. But the issue is that I am getting an error for exceeding the limit size but the zip file is only 500KB but when I print the total size of the message at the end i see 35MB !!. Any help in understanding this is greatly appreciated ! Thanks
zf = open(newZip+".zip","rb")
msg = MIMEMultipart()
msg['From'] = os.environ['EMAIL_USER']
msg['To'] = email
msg['Date'] = formatdate(localtime = True)
msg['Subject'] = "Results - "+email
msg.attach (MIMEText("textMessage"))
part = MIMEBase('application', "octet-stream")
part.set_payload(zf.read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename='+newZip+".zip")
msg.attach(part)
server = smtplib.SMTP_SSL("smtp.gmail.com", 465)
server.ehlo()
server.login(os.environ['EMAIL_USER'], os.environ['EMAIL_PASSWORD'])
server.sendmail(os.environ['EMAIL_USER'], email, str(msg))
max_limit_in_bytes = int( server.esmtp_features['size'] )
print(max_limit_in_bytes)
print("***********")
server.close()
I'm having a weird problem with sending out e-mail from a python script.
This one works perfectly:
msg = MIMEText(body)
msg['Subject'] = 'Booking confirmation %s, %s.'% (tourname, tourdatetime.strftime('%d %b %Y, %H:%M'))
msg['From'] = FROMADDRESS
msg['To'] = email
msg['Cc'] = OWNERADDRESS
s = smtplib.SMTP(MAILSERVER)
s.sendmail(FROMADDRESS, [email, OWNERADDRESS], msg.as_string())
s.quit()
The received e-mail looks exactly as I expect it to.
From the same server, the following snippet doesn't work properly: the e-mail is sent out to the correct recipients, the attachment is there, but the To: and the Cc: headers are missing from the mail that's been received. The subject, body and From: are set correctly.
msg = MIMEMultipart()
msg['Subject'] = subject
msg['From'] = FROMADDRESS
msg['To'] = data['email']
msg['Cc'] = OWNERADDRESS
msg.attach(MIMEText(body))
part = MIMEBase('application', "octet-stream")
part.set_payload(
file(
os.path.join(
directory, '../images', 'meetingpoint_%s.jpg'% (data['tourid'], ))
).read())
Encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="%s"' % ('meetingpoint_%s.jpg'% (data['tourid'], ), ))
msg.attach(part)
smtp.sendmail(FROMADDRESS, [data['email'], OWNERADDRESS], msg.as_string())
I am trying to send an email with an image using smtplib in python. The email shows up fine on my desktop and on the iphone gmail app, but on the standard iphone mail app the body doesn't appear. Here is my code:
def send_html_email(self, subject, html, to_email,from_email, password, from_name, image=None):
msg = MIMEMultipart('alternative')
msg['From'] = from_name
msg['To'] = to_email
msg['Subject'] = subject
html_message = MIMEText(html, "html")
msg.attach(html_message)
if image:
msgImage = MIMEImage(image)
msgImage.add_header('Content-ID', '<image1>')
msg.attach(msgImage)
session = smtplib.SMTP("smtp.gmail.com:587")
session.starttls()
session.login(from_email, password)
session.sendmail(from_email, to_email, msg.as_string().encode('utf-8'))
session.quit()
It seems that when I do not add an image, the email sends fine with the body. Any ideas on how to get it working with the image as well?
This appears to work:
def send_html_email(self, subject, html, to_email, from_email, password, from_name, image=None):
msgRoot = MIMEMultipart('related')
msgRoot['From'] = from_name
msgRoot['To'] = to_email
msgRoot['Subject'] = subject
msg = MIMEMultipart('alternative')
msgRoot.attach(msg)
html_message = MIMEText(html, "html")
msg.attach(html_message)
if image:
msgImage = MIMEImage(image)
msgImage.add_header('Content-ID', '<image1>')
msgRoot.attach(msgImage)
session = smtplib.SMTP("smtp.gmail.com:587")
session.starttls()
session.login(from_email, password)
session.sendmail(from_email, to_email, msgRoot.as_string().encode('utf-8'))
session.quit()