Missing headers when sending mail from python - python

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())

Related

How to use python to send emails with multiple attachments

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()

Python Email Size is way bigger than the zip file using smtplib

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()

Send mail from Python using smtp, no content in mobile phone

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()

Email multiple recipients Python

I'm trying to email multiple recipients using the pyton script below. I've searched the forum for answers, but have not been able to implement any of them correctly. If anyone has a moment to review my script and spot/resolve the problem it would be greatly appreciated.
Here's my script, I gather my issue is in the 'sendmail' portion, but can't figure out how to fix it:
gmail_user = "sender#email.com"
gmail_pwd = "sender_password"
recipients = ['recipient1#email.com','recipient2#email.com']
def mail(to, subject, text, attach):
msg = MIMEMultipart()
msg['From'] = gmail_user
msg['To'] = ", ".join(recipients)
msg['Subject'] = subject
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())
mailServer.close()
mail("recipient1#email.com, recipient2#email.com",
"Subject",
"Message",
"attchachment")
Any insight would be greatly appreciated.
Best,
Matt
It should be more like
mail(["recipient1#email.com", "recipient2#email.com"],
"Subject",
"Message",
"attchachment")
You already have a array of recipients declared,that too globally,You can use that without passing it as an argument to mail.
I wrote this bit of code to do exactly what you want. If you find a bug let me know (I've tested it and it works):
import email as em
import smtplib as smtp
import os
ENDPOINTS = {KEY: 'value#domain.com'}
class BoxWriter(object):
def __init__(self):
pass
def dispatch(self, files, box_target, additional_targets=None, email_subject=None, body='New figures'):
"""
Send an email to multiple recipients
:param files: list of files to send--requires full path
:param box_target: Relevant entry ENDPOINTS dict
:param additional_targets: other addresses to send the same email
:param email_subject: optional title for email
"""
destination = ENDPOINTS.get(box_target, None)
if destination is None:
raise Exception('Target folder on Box does not exist')
recipients = [destination]
if additional_targets is not None:
recipients.extend(additional_targets)
subject = 'Updating files'
if email_subject is not None:
subject = email_subject
message = em.MIMEMultipart.MIMEMultipart()
message['From'] = 'user#domain.com'
message['To'] = ', '.join(recipients)
message['Date'] = em.Utils.formatdate(localtime=True)
message['Subject'] = subject
message.attach(em.MIMEText.MIMEText(body + '\n' +'Contents: \n{0}'.format('\n'.join(files))))
for f in files:
base = em.MIMEBase.MIMEBase('application', "octet-stream")
base.set_payload(open(f, 'rb').read())
em.Encoders.encode_base64(base)
base.add_header('Content-Disposition', 'attachment; filename={0}'.format(os.path.basename(f)))
message.attach(base)
conn = smtp.SMTP('smtp.gmail.com', 587)
un = 'user#gmail.com'
pw = 'test1234'
conn.starttls()
conn.login(un, pw)
conn.sendmail('user#domain.com', recipients, message.as_string())
conn.close()
I was facing the same issue, I fixed this issue now. Here is my code -
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import smtplib
import datetime
def sendMail():
message = MIMEMultipart()
message["To"] = "xxxxx#xxxx.com,yyyy#yyyy.com"
message["Cc"] = "zzzzzz#gmail.com,*********#gmail.com"
message["From"] = "xxxxxxxx#gmail.com"
message["Password"] = "***************"
server = 'smtp.gmail.com:587'
try:
now = datetime.datetime.now()
message['Subject'] = "cxxdRL Table status (Super Important Message) - "+str(now)
server = smtplib.SMTP(server)
server.ehlo()
server.starttls()
server.login(message["From"], message["Password"])
server.sendmail(message["From"], message["To"].split(",") + message["Cc"].split(","), message.as_string())
server.quit()
print('Mail sent')
except:
print('Something went wrong...')
sendMail()

Python sendmail with Cc

I already programmed a function which sends mails with atachments, images on text and other things, but now I need the function to use de Cc (Carbon Copy) function in order to send copies to different emails.
I have done some changes on the function and it works but not as I want.
THe email is sent to the address ("toaddr") and the mail shows that there are other emails added as Cc("tocc") emails, but the Cc emails do not recieve the email.
To be more clear (because I think I am not being very clear) here is an example:
Sender: from#hotmail.com
Receiver: to#hotmail.com
Copied: cc#hotmail.com
to#hotmail.com receives the email and can see that cc#hotmail.com is copied on it.
cc#hotmail.com does not get the email.
if to#hotmail.com reply to all the email, THEN cc#hotmail gets the email.
Can anyone help me telling me what do I need to change on the function?? I guees the problem is with the server.sendmail() function
This is my function:
def enviarCorreo(fromaddr, toaddr, tocc, subject, text, file, imagenes):
msg = MIMEMultipart('mixed')
msg['From'] = fromaddr
msg['To'] = ','.join(toaddr)
msg['Cc'] = ','.join(tocc) # <-- I added this
msg['Subject'] = subject
msg.attach(MIMEText(text,'HTML'))
#Attached Images--------------
if imagenes:
imagenes = imagenes.split('--')
for i in range(len(imagenes)):
adjuntoImagen = MIMEBase('application', "octet-stream")
adjuntoImagen.set_payload(open(imagenes[i], "rb").read())
encode_base64(adjuntoImagen)
anexoImagen = os.path.basename(imagenes[i])
adjuntoImagen.add_header('Content-Disposition', 'attachment; filename= "%s"' % anexoImagen)
adjuntoImagen.add_header('Content-ID','<imagen_%s>' % (i+1))
msg.attach(adjuntoImagen)
#Files Attached ---------------
if file:
file = file.split('--')
for i in range(len(file)):
adjunto = MIMEBase('application', "octet-stream")
adjunto.set_payload(open(file[i], "rb").read())
encode_base64(adjunto)
anexo = os.path.basename(file[i])
adjunto.add_header('Content-Disposition', 'attachment; filename= "%s"' % anexo)
msg.attach(adjunto)
#Send ---------------------
server = smtplib.SMTP('localhost')
server.set_debuglevel(1)
server.sendmail(fromaddr,[toaddr,tocc], msg.as_string()) #<-- I modify this with the tocc
server.quit()
return
In your sendmail call, you're passing [toaddr, tocc] which is a list of lists, have you tried passing toaddr + tocc instead?

Categories

Resources