4
votes

I found dart plugin called mailer3: "^1.1.9". Previously I create an image in mobile temp directory. In Flutter mobile app I try to send this saved picture using mailer3 plugin as a mail. The mail reach the destination, I don't get error but seems lost the attachment in process.

In dart it works very well and send the attachment as well. In flutter I can use the temp directory to show the image in app but cannot be able attache to mail.

The image location is in the temp folder of the device:

  • '/data/user/0/com.myApp.myApp/app_flutter/20180700087.jpg'

I can show the image using below code:

  • new FileImage(File('$newDekontImage'),

Error:

E/flutter (21184): [ERROR:topaz/lib/tonic/logging/dart_error.cc(16)] Unhandled exception:
E/flutter (21184): FileSystemException: Cannot open file, path = '/data/user/0/com.myApp.myApp/app_flutter/20180700087.jpg' (OS Error: No such file or directory, errno = 2)

How to send mail with attachments in Flutter with provided information in this question?

The Flutter Code:

// TODO: SEND MAIL
void _sendMail() async {
  if (!_formKey.currentState.validate()) {
    return;
  } else {
    _formKey.currentState.save();

    var _options = new GmailSmtpOptions()
    ..username = “[email protected]"
    ..password = “myPassword”;

    var _emailTransport = new SmtpTransport(_options);
    var _envelope = new Envelope()
    ..from = "[email protected]"
    ..recipients.add(_receiverMailAddress)
      ..subject = "${_userDekontDetails[0][0].toString()} - Receipt”
      ..attachments.add(await new Attachment(file: await new File('$newDekontImage')))
      ..text = "${_userDekontDetails[0][0].toString()} - Receipt"
      ..html = '<h3>${_userDekontDetails[0][0].toString()} Receipt.</h3>'
          '<p>Hi, registered under my name, I am sending the receipt (${widget._currentUserReceiptNo}) with attached to this mail.</p>'
          '<p></p>'
          '<h5>Regards, </br></h5>'
          '${_userDekontDetails[0][0].toString()}';

    _emailTransport.send(_envelope)
      ..then((envelope) => print('Email sent'))
      ..catchError((e) => print('Error occured: $e'));
  }
}
2
I found that it send the attachment to private mail, but it doesnt send attachment to gmailNick
I think you can refer this forum: stackoverflow.com/questions/57903718/…New User

2 Answers

0
votes

As of this writing, the mailer3 plugin is outdated and mailer is the most up-to-date plugin for sending emails. The mailer plugin currently contains important fixes that mailer2 and mailer3 has. I suggest opting to use mailer package instead of mailer3.

Here's a port of your code snippet from mailer3 to mailer

_sendMail(String username, String accessToken) async {
  // Read https://pub.dev/documentation/mailer/latest/smtp_server_gmail/gmailSaslXoauth2.html
  var _emailTransport = gmailSaslXoauth2(username, accessToken);

  var _envelope = new Message()
    ..from = "[email protected]"
    ..recipients.add("[email protected]")
    ..subject = '{EMAIL_SUBJECT_GOES_HERE}'
    // Read https://pub.dev/documentation/mailer/latest/mailer/FileAttachment-class.html
    ..attachments
        .add(FileAttachment(File('{FILE_PATH}')))
    ..text = '{PLAIN_TEXT_GOES_HERE}'
    ..html = '{HTML_CONTENT_GOES_HERE}';

  send(_envelope, _emailTransport)
    ..then((envelope) => print('Email sent'))
    ..catchError((e) => print('Error occured: $e'));
}
0
votes

I have used enough_mail, Hope it will be helpful.

MessageBuilder messageBuilder = MessageBuilder();

Future<bool> onFileSelect(BuildContext context) async {
    final result = await FilePicker.platform
        .pickFiles(type: FileType.any, allowMultiple: true, withData: true);
    if (result == null) {
      return false;
    }
    for (final file in result.files) {
      final lastDotIndex = file.path.lastIndexOf('.');
      MediaType mediaType;
      if (lastDotIndex == -1 || lastDotIndex == file.path.length - 1) {
        mediaType = MediaType.fromSubtype(MediaSubtype.applicationOctetStream);
      } else {
        final ext = file.path.substring(lastDotIndex + 1);
        mediaType = MediaType.guessFromFileExtension(ext);
      }
      messageBuilder.addBinary(file.bytes, mediaType, filename: file.name);
    }
    return true;
}

Future<void> sendMail(BuildContext buildContext) async {

    setState(() {
      needToFreezeUi = true;
    });

    MySnackBar.show(buildContext, MySnackBar.loadingIcon, "Please wait...!");
    
    SmtpClient smtpClient = SmtpClient(domain, isLogEnabled: true);
    try {
      await smtpClient.connectToServer(
        "$serverPrefix.${userInfo.domainName}",
        smtpServerPort,
        isSecure: isSmtpServerSecure
      );
      await smtpClient.ehlo();
      await smtpClient.authenticate(userInfo.email, userInfo.password);
      messageBuilder.from = [MailAddress('', userInfo.email)];
      messageBuilder.to = [MailAddress('', toTextEditCtl.text)];
      messageBuilder.cc = selectedCCEmailInfos.map((e) => MailAddress('',e.emailAddress)).toList();
      messageBuilder.bcc = selectedBCCEmailInfos.map((e) => MailAddress('',e.emailAddress)).toList();
      messageBuilder.subject = subjectTextEditCtl.text;
      String htmlText = await htmlEditorController.getText();
      messageBuilder.addTextHtml(htmlText);

      messageBuilder.hasAttachments ? messageBuilder.getPart(
          MediaSubtype.multipartAlternative,
          recursive: false
      ) : messageBuilder.addPart(
          mediaSubtype: MediaSubtype.multipartAlternative,
          insert: true
      );

      if (!messageBuilder.hasAttachments) {
        messageBuilder.setContentType(
            MediaType.fromSubtype(MediaSubtype.multipartAlternative)
        );
      }

      MimeMessage mimeMessage = messageBuilder.buildMimeMessage();
      SmtpResponse smtpResponse = await smtpClient.sendMessage(mimeMessage);

      MySnackBar.hide(buildContext);
      if(smtpResponse.isOkStatus){
        MySnackBar.show(buildContext,MySnackBar.successIcon,"Mail send successfully");
        clearInputFields(buildContext);
      }else {
        MySnackBar.show(buildContext,MySnackBar.errorIcon,"Something went wrong, please try again!");
      }
      
    } on SmtpException catch (e) {
      MySnackBar.show(buildContext,MySnackBar.errorIcon,"Something went wrong, please try again!");
    }
    setState(() {
      needToFreezeUi = false;
    });
}

============================

dependencies:
  enough_mail: ^1.3.4
  html_editor_enhanced: ^1.4.0
  file_picker: ^3.0.2+2