TalkToMeSenpai
TalkToMeSenpai

Reputation: 11

Sending email with mailer flutter package on Smtp outlook provider

I'm trying to send an email with the latest version of the flutter mailer package. I also want to use outlook as the smtp server.I configured an azure account to get my application token in order to achieve this which I currently can't. I'm following the example of the gmail version but I want to use the smtp function in the mailer package.

Flutter Mailer

I gave offline_access, SMTP.Send and User.Read permissions to the API that I configured. I'm getting this error

 " Error occurred while sending email: Authentication Failed (code: 535), response:< 5.7.139 Authentication unsuccessful, the user credentials were incorrect"

This is my current code in dart to send the email:

final smtpServer = SmtpServer('smtp-mail.outlook.com',
          port: 587,
          ignoreBadCertificate: true,
          ssl: false,
          allowInsecure: true,
          username: username,
          password: password,
          xoauth2Token: xoauth2Token);

      final message = Message()
        ..from = const Address(username,
            'This message')
        ..recipients.add(user?.email ?? 'unknown user')
        ..subject = 'Hi I'm a message'
        ..text = 'Hello World';

      final sendReport = await send(message, smtpServer);

Upvotes: 1

Views: 50

Answers (1)

Sampath
Sampath

Reputation: 3639

The issue is an authentication failure when attempting to send an email via Outlook's SMTP server. According to this Microsoft documentation, we need the following roles and permissions:

  • Microsoft.Communication/CommunicationServices/Read
  • Microsoft.Communication/CommunicationServices/Write
  • Microsoft.Communication/EmailServices/Write
  • SMTP.Send
  • User.Read, Reader, acs mail sending

Below is the Dart code used for sending an email:

void main() async {
  String smtpAuthUsername = "<Azure Communication Services Resource name>|<Entra Application Id>|<Entra Application Tenant Id>";
  String smtpAuthPassword = "<Entra Application Client Secret>";
  String sender = "[email protected]"; 
  String recipient = "[email protected]";
  String subject = "Welcome to Azure Communication Service Email SMTP";
  String body = "Hello world via email.";
  final smtpServer = SmtpServer(
    'smtp-mail.outlook.com',
    port: 587,
    username: smtpAuthUsername,
    password: smtpAuthPassword,
    ignoreBadCertificate: true,
    ssl: false,
    allowInsecure: true,
  );

  final message = Message()
    ..from = Address(sender, 'Azure Communication Service')
    ..recipients.add(recipient)
    ..subject = subject
    ..text = body;

  try {
    final sendReport = await send(message, smtpServer);
    print('Message sent: ${sendReport.toString()}');
  } on MailerException catch (e) {
    print('Message not sent.');
    for (var p in e.problems) {
      print('Problem: ${p.code}: ${p.msg}');
    }
  }
}

mail

Upvotes: 1

Related Questions