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?
Related
I have to sendmail at the end of my code with csv attached containing a dataframe.
Im doing it at AWS Lambda using boto3 to call SES as it follows.
def sendMail1(value, df):
subject = "Comission"
client = boto3.client("ses")
body = f"""
Comission value is {value}.
"""
message = {"Subject": {"Data": subject}, "Body": {"Html": {"Data": body}}}
attachment = df.to_csv(f"Comission.csv", index=False)
response = client.send_email(Source = "myemail#gmail.com", Destination = {"ToAddresses": ["youremail#gmail.com"]}, Message = message, Attachment = attachment)
I had no ideia how to do it, I tried df.to_csv method and include it as attachment. Did not work.
The rest of the code works without the attachment parts, but I need to attach my df to the e-mail.
Do you guys have any idea how to do it?
df.to_csv(f"Comission.csv", index=False)
to_emails = [target_email1, target_email2]
ses = boto3.client('ses')
msg = MIMEMultipart()
msg['Subject'] = 'weekly report'
msg['From'] = from_email
msg['To'] = to_emails[0]
# what a recipient sees if they don't use an email reader
msg.preamble = 'Multipart message.\n'
# the message body
part = MIMEText('Howdy -- here is the data from last week.')
msg.attach(part)
# the attachment
part = MIMEApplication(open('Comission.csv', 'rb').read())
part.add_header('Content-Disposition', 'attachment', filename='Comission.csv')
msg.attach(part)
result = ses.send_raw_email(
Source=msg['From'],
Destinations=to_emails,
RawMessage={'Data': msg.as_string()})
# and send the message
print result
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 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.
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'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()