Hello experts,
am trying to get the filename of attachments from email,
Am using this expression: CType(item.Attachments.FirstOrDefault, Attachment).Name
but am getting an error: Object reference not set to an instance of an object.
Anyone who can help?
Hey @pattwagunyi
Mail attachments is a collection.
You can either use ForEach or get it by index.
item.Attachments(0).Name
But provided the mail has some attachments.
Thanks
#nK
its inside a for each loop already
Am using the expression inside a loop
Your expression looks good on my end:
Did you check if the mail that you’re checking contains attachments? If the mail does not have attachments, the expression above fails.
Another thing you can check is that the ForEach has the correct Type (as there are other variable types named the same:
System.Net.Mail.MailMessage
Hey @pattwagunyi
The ForEach you are currently using is to iterate emails but not the attachments.
You need to have a nested ForEach or the current statement which you use is fine to fetch first attachment but the email should have atleast one attachment for your query to work.
But just simplifying your statement
item.Attachments.FirstOrDefault().Name
If you need to avoid the error when there is no attachment, just try the below.
If(item.Attachments.Count > 0, item.Attachments.FirstOrDefault().Name, "No Attachments Found")
Hope this helps.
Thanks
#nK
This has worked, thank you
Cool, Hope you understood the logic. If not please let me know. Thanks
This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.