Search code examples
emailsmtpansible

Ansible mail module not working with office 365


I am trying to send send an email from ansible

If I try it with gmail it works perfectly, However If I try with office 365 its not working.

Below is my Playbook.

---
  - name: Mail Sendig using Ansible
    hosts: localhost
    tasks:
      - name: Mail sending using Mail Module
        mail:
          host: "smtp.office365.com"
          port: 587
          username: "dcalert@mycompany.com"
          password: "mypasswd"
          to: "Jon Snow <jon.snow@mycompany.com>"
          subject: "Ansible"
          body: "Hello from Ansible"
          secure: starttls

I am getting below error

ASK [Send email]
*******************************************************************
An exception occurred during task execution. To see the full 
traceback, use -vvv. The error was: SMTPSenderRefused: (501, '5.1.7 
Invalid address', 'root')
fatal: [localhost -> localhost]: FAILED! => {"changed": false, 
"failed": true, "msg": "Failed to send mail to 
jon.snow@mycompany.com: (501, '5.1.7 Invalid address', 
'root')", "rc": 1}

Solution

  • You're missing fromparameter...

    Take a look here: Ansible Mail Module

    It says the parameter from defaults to root. Since you're not setting it, mail server says its invalid. Probably gmail doesnt handle it the same way as office365.

    Give this a try...

    ---
      - name: Mail Sendig using Ansible
        hosts: localhost
        tasks:
          - name: Mail sending using Mail Module
            mail:
              host: "smtp.office365.com"
              port: 587
              username: "dcalert@mycompany.com"
              password: "mypasswd"
              from: "dcalert@mycompany.com"
              to: "Jon Snow <jon.snow@mycompany.com>"
              subject: "Ansible"
              body: "Hello from Ansible"
              secure: starttls