问题描述
我正在使用依赖项 https://pub.dev/packages/mailer 通过 Flutter Web 应用程序发送自动消息,我正在使用以下代码。
String username="************";
String password = "*******";
var smtpServer = gmail(username,password);
final message = Message()
..from = Address(username,'Truck App')
..recipients.add('******')
..subject = 'Testing'
..text = msg.text
..html = "<h1>Test</h1>\n<p> hey! Here\'s some text</p>";
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}');
}
}
final equivalentMessage = Message()
..from = Address(username,'Your name ?')
..recipients.add(Address('******'))
..ccRecipients.addAll([Address('******')])
..bccRecipients.add('*********')
..subject = 'Test Dart Mailer library :: ? ::'
..text = 'This is the plain text.\nThis is line 2 of the text part.'
..html = '<h1>Test</h1>\n<p>hey! Here is some HTML content</p>';
final sendReport2 = await send(equivalentMessage,smtpServer);
var connection = PersistentConnection(smtpServer);
await connection.send(message);
await connection.send(equivalentMessage);
await connection.close();
但我收到这样的错误:
js_helper.dart:1130 Uncaught Unsupported operation: Socket constructor
at Object.b (http://localhost:52881/main.dart.js:4220:3)
at Object.aVb (http://localhost:52881/main.dart.js:8007:31)
at Object.aVc (http://localhost:52881/main.dart.js:8034:5)
at http://localhost:52881/main.dart.js:79815:14
at awO.a (http://localhost:52881/main.dart.js:5925:71)
at awO.$2 (http://localhost:52881/main.dart.js:38402:23)
at Object.W (http://localhost:52881/main.dart.js:5911:19)
at Ku.yv (http://localhost:52881/main.dart.js:79822:10)
at http://localhost:52881/main.dart.js:25197:14
at awO.a (http://localhost:52881/main.dart.js:5925:71)
解决方法
Socket
对象无法在 Web 上构建,因为它们来自 dart:io
,编译为 JS 时不可用。
在 pub.dev 上查看软件包时,您将能够看到支持的平台。如果您转到 https://pub.dev/packages/mailer,您会注意到它仅支持 Dart 原生,而支持的 Flutter 平台缺少 web
所以在这里我得到了这个问题的答案,正如cameron1024在前面的回答中提到的,这段代码是可压缩的,并且在android平台上运行良好(经过测试)但是当你尝试将它集成到网络平台时会抛出同样的错误.
所以要通过网络平台发送邮件,您可以使用 pub.dev 上提供的 sendgrid_mailer 包
使用sendgrid _mailer需要有api key,可以从sendgrid官网获取。
谢谢