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.
Related
I have this piece of code:
l = ["Jargon", "Hello", "This", "Is", "Great"]
result = "\n".join(l[1:])
print result
output:
Hello
This
Is
Great
And I am trying to print this to a body of an email as shown below, I am getting the text as an attachment rather than as-body. can anyone please tell me if I am missing something here?
msg = MIMEMultipart()
msg["From"] = emailfrom
msg["To"] = emailto
ctype, encoding = mimetypes.guess_type(fileToSend)
if ctype is None or encoding is not None:
ctype = "application/octet-stream"
maintype, subtype = ctype.split("/", 1)
fp = open(file.csv, 'r')
attachment = MIMEBase(maintype, subtype)
attachment.set_payload(fp.read())
fp.close()
encoders.encode_base64(attachment)
attachment.add_header("Content-Disposition", "attachment", fileame='file.csv')
msg.attach(attachment)
msg.attach(MIMEText(result, "plain"))
server = smtplib.SMTP("localhost")
server.sendmail(emailfrom, emailto, msg.as_string())
server.quit()
When using yagmail, it works as intended.
import yagmail
yag = yagmail.SMTP(
user=conf_yag['user'],
password=conf_yag['password'])
l = ["Jargon", "Hello", "This", "Is", "Great"]
result = "\n".join(l[1:])
yag.send(emailto, 'test from yagmail', result)
# including attachment
yag.send(emailto,
subject='test from yagmail',
contents=result,
attachments='somefile.txt')
where conf_yag stores your credentials, emailto is the receiver email address, and 'somefile.txt' is the file attachment.
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 need to send multiple emails (like 200 customized emails each day), but all have same pdf attachment. Is it possible to upload the attachment only once to save on upload time?
Even better than that, is it possible to upload the file only once on a google server and each day just reference that file?
Just for reference here is the code (modified a bit from google developer sample code):
# main function
def SendMessageAttachment(sender, to, subject, msgHtml, msgPlain, attachmentFile):
credentials = get_credentials()
http = credentials.authorize(httplib2.Http())
service = discovery.build('gmail', 'v1', http=http)
message1 = create_message_with_attachment(sender, to, subject, msgPlain, attachmentFile)
SendMessageInternal(service, "me", message1)
def SendMessageInternal(service, user_id, message):
try:
message = (service.users().messages().send(userId=user_id, body=message).execute())
print 'Message Id: %s' % message['id']
return message
except errors.HttpError, error:
print 'An error occurred: %s' % error
def create_message_with_attachment(
sender, to, subject, message_text, attachmentFile):
"""Create a message for an email.
Args:
sender: Email address of the sender.
to: Email address of the receiver.
subject: The subject of the email message.
message_text: The text of the email message.
file: The path to the file to be attached.
Returns:
An object containing a base64url encoded email object.
"""
message = MIMEMultipart()
message['to'] = to
message['from'] = sender
message['subject'] = subject
msg = MIMEText(message_text)
message.attach(msg)
print "create_message_with_attachment: file:", attachmentFile
content_type, encoding = mimetypes.guess_type(attachmentFile)
if content_type is None or encoding is not None:
content_type = 'application/octet-stream'
main_type, sub_type = content_type.split('/', 1)
if main_type == 'text':
fp = open(attachmentFile, 'rb')
msg = MIMEText(fp.read(), _subtype=sub_type)
fp.close()
elif main_type == 'image':
fp = open(attachmentFile, 'rb')
msg = MIMEImage(fp.read(), _subtype=sub_type)
fp.close()
elif main_type == 'audio':
fp = open(attachmentFile, 'rb')
msg = MIMEAudio(fp.read(), _subtype=sub_type)
fp.close()
else:
fp = open(attachmentFile, 'rb')
msg = MIMEBase(main_type, sub_type)
msg.set_payload(fp.read())
fp.close()
filename = os.path.basename(attachmentFile)
msg.add_header('Content-Disposition', 'attachment', filename=filename)
message.attach(msg)
return {'raw': base64.urlsafe_b64encode(message.as_string())}
the attachment is loaded here:
part = MIMEApplication(open("mypdf.pdf","rb").read())
but the reference for the header can be anywhere
part.add_header('Content-Disposition', 'attachment', filename="file.pdf")
msg.attach(part)
You could write a function to add this header before sending the mail and iterate over all your recipients.
matches = []
for root, dirnames, filenames in os.walk('C:\Users\top\UDI\New folder'):
for filename in fnmatch.filter(filenames, '*.html'):
matches.append(os.path.join(root, filename))
filename = root.rstrip(os.sep) + os.sep+ filename
#print filename
fromaddress = 'ucm_embed_test'
toaddress = "hetappa#ace.com, hepa#gmail.com"
text = "Test is Parsed"
msg = MIMEMultipart('alternative')
msg['From'] =fromaddress
msg['To'] = toaddress
msg['Subject'] = text
print "Sending mail"
ctype, encoding = mimetypes.guess_type(filename)
if ctype is None or encoding is not None:
ctype = "application/octet-stream"
maintype, subtype = ctype.split("/", 1)
with open(filename) as fp:
attachment = MIMEText(fp.read(), _subtype=subtype)
attachment.add_header("Content-Disposition", "attachment",\
filename=os.path.basename(filename))
msg.attach(MIMEText(open(filename).read(), "text/html"))
server = smtplib.SMTP('eu-smtp.nuae.com')
server.ehlo()
#server.starttls()
#server.login(username,password)
server.sendmail(fromaddress,toaddress.split(','),msg.as_string())
server.quit()
I am reading a .html file and later sending it as an email to the respective person. But the message body appeared in the email is in the form of html tags. how to represent my answers as the characters in the message body. Can someone help me in this ?
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?