Flutter – Sending Email with Attachment
To send an email with attachment in a Flutter application, you can use the ‘mailer’ package. Here’s an example of how to implement it:
Step 1: Add dependency
In your pubspec.yaml file, add the following dependency:
dependencies:
mailer: ^5.0.0
Step 2: Import required packages
In your Dart file, import the necessary packages:
import 'package:mailer/mailer.dart';
import 'package:mailer/smtp_server.dart';
Step 3: Write code for sending email
Here’s a sample code to send an email with attachment:
void sendEmailWithAttachment() async {
String username = 'your-email@gmail.com';
String password = 'your-password';
final smtpServer = gmail(username, password);
final message = Message()
..from = Address(username, 'Your Name')
..recipients.add('recipient-email@gmail.com')
..subject = 'Flutter Email Test'
..text = 'This is the plain body of the message. Attachments are supported.'
..attachments = [
FileAttachment(File('path/to/attachment.pdf'))
];
try {
final sendReport = await send(message, smtpServer);
print('Message sent: ${sendReport.sent}');
} catch (e) {
print('Error occurred: $e');
}
}
- Replace ‘your-email@gmail.com’ with your own email address.
- Replace ‘your-password’ with your email account password.
- Replace ‘recipient-email@gmail.com’ with the recipient’s email address.
- Replace ‘path/to/attachment.pdf’ with the actual path to your attachment file.
Step 4: Call the method
Finally, call the ‘sendEmailWithAttachment()’ method to send the email.
sendEmailWithAttachment();
Make sure you have the necessary permissions, such as internet access, in your Android and iOS manifest files.