I need to send an email with a generated pdf attached.
Right now, I managed to generate pdfs and I can save them to the phone memory, for this I follow this post: Export Flutter application screen to PDF
But now I want to attach it automatically to and email and send it. With the info in that post it is impossible. Because it leads me to an screen in which I must select the pdf parameters and the pdf name.
Here is the code I used to generate the PDF:
void printScreen() {
Printing.layoutPdf(onLayout: (PdfPageFormat format) async {
final doc = pw.Document();
final image = await WidgetWraper.fromKey(
key: printKey,
pixelRatio: 2.0,
);
doc.addPage(pw.Page(
pageFormat: format,
build: (pw.Context context) {
return pw.Center(
child: pw.Expanded(
child: pw.Image(image),
),
);
}));
return doc.save();
});
}
To send emails I am reading the documentation of the Flutter Email Sender Package But I don't know how to generate the PDF automatically with a predefined name, attach it to the email and then, send it.
As you have mentioned that you are able to generate PDF's and save them in phone memory, now you just need to pass attachments path(where attachment file is saved) in Email constructor like this.
Complete Send method code.
Future<void> send() async {
final Email email = Email(
body: _bodyController.text,
subject: _subjectController.text,
recipients: [_recipientController.text],
attachmentPaths: attachments,
isHTML: isHTML,
);
String platformResponse;
try {
await FlutterEmailSender.send(email);
platformResponse = 'success';
} catch (error) {
print(error);
platformResponse = error.toString();
}
if (!mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(platformResponse),
),
);
}