Home > Back-end >  Add multiple recipient while sending mail throws error - python
Add multiple recipient while sending mail throws error - python

Time:11-24

I have a code that should send mail to multiple recipient , but it throws me error when i use multiple recipients.

The error am getting -

{'error': {'code': 'RequestBodyRead', 'message': "The property 'Email Address' does not exist on type 'microsoft.graph.recipient'. Make sure to only use property names that are defined by the type or mark the type as open type."}}

def send_email(token, subject, recipients=None, body= None, content_type='HTML', attachments=None):
    try:
        print("inside send mail")
        userId = str(EmailID)
        graph_url = f'https://graph.microsoft.com/v1.0/users/{userId}/sendMail'
        # Verify that required arguments have been passed.
        if not all([token, subject, recipients]):
            raise ValueError('sendmail(): required arguments missing')
        # Create recipients list in required format.

        recipient_list = [{'Email Address': {'Address': address}} for address in recipients]
        print(recipient_list)
        # Create list of attachments in required format.
        attached_files = []
        if attachments:
            for filename in attachments:
                b64_content = base64.b64encode(open(filename, 'rb').read())
                mine_type = mimetypes.guess_type(filename)[0]
                mime_type = mime_type or ''
                attached_files.append(
                    {'@odata. type': '#microsoft. graph. fi LeAttachment',
                     'ContentBytes': b64_content.decode('utf-8'),
                     'ContentType': mime_type,
                     'Name': filename})

        email_msg = {'Message': {'Subject': subject,
                                 'Body': {'ContentType': content_type, 'Content': body},
                                 'ToRecipients': recipient_list,
                                 'Attachments': attached_files},
                     'SaveToSentItems': 'true'}

        res = requests.post(
            graph_url,
            headers={
                'Authorization': 'Bearer {0}'.format(token),
                'Content-Type': 'application/json'
            },
            data=json.dumps(email_msg))
        print(res.json())
    except Exception as e:
        print(e)

So when printing recipient_list am getting [{'Email Address': {'Address': '[email protected]'}}, {'Email Address': {'Address': 'harry @company.com'}}]

Can anyone please help me solve this issue

CodePudding user response:

The name of the property inside toRecipients is emailAddress not Email Address.

Simply remove the space.

recipient_list = [{'emailAddress': {'Address': address}} for address in recipients]

Also in attachments you have some spaces: '@odata. type': '#microsoft. graph. fi LeAttachment'.

Remove those spaces

attached_files.append(
                {'@odata.type': '#microsoft.graph.fileAttachment',
                 'ContentBytes': b64_content.decode('utf-8'),
                 'ContentType': mime_type,
                 'Name': filename})

There is no reason to call res.json() because this request doesn't return any response body.

User sendMail response

  • Related