Error receiving email attachments

What I’m trying to do:
I’m trying to display and save email attachments but the code only replies to my email and does not print or save any attachments I send. Could there be a glitch in my setup?

Code Sample:

@anvil.email.handle_message()
def message_handler(msg):
  for attachment in msg.attachments:
    app_tables.received_files.add_row(file=attachment, frm=msg.envelope.sender)
    print ("attachment: " + attachment)
  msg.reply(text="Received")   

Clone link:
(Anvil | Login)

EDIT: I updated the code so it should send back any attachments received, to help test:

@anvil.email.handle_message
def message_handler(msg):  
  for att in msg.attachments:
    print ("attachment: " + att.name)
    app_tables.received_files.add_row(file=att)
  
  anvil.email.send(to=msg.envelope.from_address, from_name='hi', subject='returning', text='test', attachments=[anvil.BlobMedia(att.content_type, att.get_bytes(), name=att.name) for att in msg.attachments])
  

Are they perhaps inline attachments?

No, I send them as regular attachments

I’ve just spotted that you’re using the decorator incorrectly. It should be:

@anvil.email.handle_message
def message_handler(msg):

whereas you have:

@anvil.email.handle_message()
def message_handler(msg):

Good catch however I just fixed it and it still doesn’t print or save them

Also, having cloned your app, I sent a message and I can see an error in the app’s logs:

AttributeError: 'Envelope' object has no attribute 'sender'
at ServerModule1, line 12

That probably needs to be msg.envelope.from_address rather than msg.envelope.sender

Fixing that line means I can send a message and see the attachment in the data table but now the print call gives an error in the log.

try this instead:

print(f"attachment: {attachment.name}")

I think something is glitched on my end since the only logs I get are

Or


(from a new one I just created to test it clean)

@Steve2 As suggested by @owen.campbell it would be worth looking at the inline_attachments , which returns a dictionary. Try printing it with:

print(msg.inline_attachments)

When I clone your app and send attachments with gmail, I’ve found that they come through as inline attachments.

Also, both anvil.email.handle_message and anvil.email.handle_message() should work fine as the decorator.

2 Likes