首页 > 解决方案 > 如何使用 Dart (Flutter) 发送短信和电子邮件?

问题描述

我正在尝试在发送电子邮件和短信的颤振中构建和应用程序。目的是重置密码(忘记密码)。但我找不到合适的包。一旦用户点击重设密码,电子邮件或短信应该在没有用户交互的情况下发送。短信和电子邮件将从他们的手机发送到相同的号码或电子邮件。

任何替代建议?

标签: flutterdart

解决方案


对于电子邮件,您可以使用此邮件程序包 => https://pub.dev/packages/mailer

更新: 如果此功能不起作用,请降低您的邮件程序包版本。

例子:

Future<void> sendMail(String name, String otp, String recipientEmail) async {
  // ignore: deprecated_member_use
  SmtpServer smtpServer = gmail('yourEmail', 'Password');
  Message message = Message()
    ..from = address('yourEmail', 'UserName')
    ..recipients.add(recipientEmail)
    ..subject = 'Any Text.'
    ..html = "Any Text.";

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

对于 SMS,您可以使用 Url Launcher Package => https://pub.dev/packages/url_launcher

例子:

  _textMe() async {
if (Platform.isAndroid) {
  const uri = 'sms:YourNumber?body=hello%20there';
  await launch(uri);
  } else if (Platform.isIOS) {
  // iOS
  const uri = 'sms:YourNumber&body=hello%20there';
  await launch(uri);
  }
}

推荐阅读