I am creating an Android application with flutter/dart and I want to send an email with an embedded image inside.
So I installed flutter_email_sender and tried to use it. It works to send an email with text, but when I tried to add an image. It doesn't appear in the email application.
Here is my code:
// DataUser.pathImage is the path of the image (/data/src/0/cache/hi.jpg)
// extension(DataUser.pathImage).substring(1) => "jpg"
// DataUser.emailText.split("\n").join("<br>") is the text of the user that will be send
// ex: "Hi\nYes\nNo" => "Hi<br>Yes<br>No"
final bytes = File(DataUser.pathImage).readAsBytesSync();
String image64 = base64.encode(bytes);
String result = "<p>" + DataUser.emailText.split("\n").join("<br>") + "<br>";
result += "<img src=\"data:image/${extension(DataUser.pathImage).substring(1)};base64," + image64;
result += "\" alt=\"image\" />";
result += "</p>";
final Email email = Email(
body: result,
subject: "Pointage",
recipients: DataUser.adresse,
attachmentPaths: DataUser.filePath,
isHTML: true,
);
await FlutterEmailSender.send(email);
Is there a way to send an email containing an image with this extension?
In Email object, attachmentPaths accepts list of file paths i.e. List. You can check the complete example here.
Create a list of strings for attachments file paths:
List<String> attachments = [];
Now add your image path (string) to this list.
(I think you are doing a mistake by adding .readAsBytesSync(), I don't think that's necessary).
Let's say user picks an image from gallery:
PickedFile? pick = await picker.getImage(source: ImageSource.gallery);
if (pick != null) {
setState(() {
attachments.add(pick.path); //this line adds file path to attachments
});
}
Now pass this attachments list to the Email object.
Email(
body: result,
subject: "Pointage",
recipients: DataUser.adresse,
attachmentPaths: attachments,
isHTML: true,
);
Related
I create a flutter app and I have this one CSV file that used as a template for user. I want to provide a Button that allow user to download this CSV file, so they can use it to have CSV file that already have our template.
The problem is I don't know if the best way is to first store the file online and get the url and use it on the flutter downloader URL or keep it in the local code asset and refer to that file when user tap the download template button. Currently I'm applying the second option and it doesn't work (I don't know if this option is possible or not), the download always fail. I'm using flutter_downloader package.
How to fix this ?
Here's my code, Is something wrong with my code ?
/// Check if the file exist or not
if (await File(externalDir!.path + "/" + fileName).exists()) {
OpenFilex.open(externalDir!.path + "/" + fileName);
} else {
/// Download the file if it doesn't exist in the user's device
final String localPath = (await getApplicationDocumentsDirectory()).path;
/// Dummy file name I want use (it exist in my asset dir"
const String fileName = 'add.png';
final data = await rootBundle.load('assets/logo/add.png');
final bytes = data.buffer.asUint8List();
final File file = File('$localPath/$fileName');
await file.writeAsBytes(bytes);
/// Download the file
final taskId = await FlutterDownloader.enqueue(
url: '',
savedDir: localPath,
fileName: fileName,
showNotification: true,
openFileFromNotification: true,
);
}
To load a file from the AppBundle and then save it to the users phone, do the following:
Put the file in assets/filename.csv and declare it in your pubspec like this:
flutter:
assets:
- assets/filename.csv
Load the file in your code:
import 'package:flutter/services.dart' show ByteData, rootBundle;
(...)
var data = (await rootBundle.load('assets/filename.csv)).buffer.asInt8List();
Save the data to a file (you need the path-provider package if you want to copy the exact code):
import 'package:path_provider/path_provider.dart' as pp;
(...)
var path = (await pp.getApplicationDocumentsDirectory()).path;
var file = File('$path/filename.csv');
await file.writeAsBytes(data, flush: true);
Edit: As Stephan correctly pointed out, if you want to store the file in the downloads folder, you will find additional information about that here. Thank you Stephan!
I'm trying to only OPEN an email app i.e. Outlook, Gmail, etc. and with an attachment already attached. Ready for the user to write a subject and send it to someone. Again I'm not looking to send it automatically, only open the app with the attachment attached.
So far the only thing I found is this: https://pub.dev/packages/launchers
But I am getting an error message: "No implementation found for method send on channel GitHub.com/sunnyapp/launchers_compose"
Here is my code: I am at a loss. I feel like this should be an easy thing to do. P.S most email openers can open an email app but can't attach attachments. I also know this is for mobile only. Android and iOS.
final Email email = Email(
body: "This Email was Created by TRS to send an Excel File!",
subject: "$excelName",
recipients: [""],
attachmentPath: fullPath,
);
Iterable<String> platformResponse;
try {
final results =
await LaunchService().launch(composeEmailOperation, email);
print(results);
platformResponse = results.allAttempts.entries.map((entry) {
print("Provider = ${entry.key}\nResult = ${entry.value}");
return "P";
});
} catch (error, stack) {
print(error);
print(stack);
platformResponse = ["Error: $error"];
}
You can use https://pub.dev/packages/share_plus package:
String filename = './docs/myfile.xlsx'
Share.shareFiles([filename], text: 'This Email was Created by TRS to send an Excel File!');
This opens gmail or whatever app you have with attachment and text but this particular code only works on mobile, not on desktop. I
I use this code to save images to the gallery:
Uri uri = new Uri(baseUrl + imageName);
var img = await ImageService.Instance.LoadUrl(baseUrl + "social/social_" + imageName).AsJPGStreamAsync(quality:100);
string fileName = "Social_" + uri.ToString().Split('/').Last();
DependencyService.Get<IMediaService>().SaveImageFromStream(img, fileName);
await DisplayAlert("Saved", "Image saved to gallery!", "Ok");
the problem is, that the images do not have a time in the file, and are stored randomly in the gallery...
How can I add date to the files, so they are saved in the proper order in the gallery?
Just append something like this
DateTime.Now.ToString("MMddyyyyhhmmss");
string fileName = "Social_" + uri.ToString().Split('/').Last() + DateTime.Now.ToString("MMddyyyyhhmmss");
//03312020071656
I am working on an app in flutter, and I would like to have a "give feedback option". this form consists of 1 text field where the message is typed, and 1 button to submit and sent the feedback.
I am currently using the mailer(1) dart package to do this for me, but so far I have not been able to send and receive a mail in my inbox.
I have used flutter_mailer and mailer, both without any success. I followed instructions and tried to do the same as the example, but I can not get it working.
the show code is the method to handle the email.
void sendEmail(String message) async {
_isLoading = true;
notifyListeners();
print(message);
String username = 'matthijs******#gmail.com';
String password = '******';
final SmtpServer server = gmail(username, password);
final feedbackMessage = new Message()
..from = new Address(username, _authUser.email)
..recipients.add('m.dethmers2#hotmail.nl')
..ccRecipients.addAll([_authUser.email])
..subject = 'Feedback from ${_authUser.id} ${new DateTime.now()}'
..text = message
..html = "<h1>Test</h1>\n<p>message</p>";
final sendReports = await send(feedbackMessage, server, timeout:
Duration(seconds: 15));
_isLoading = false;
notifyListeners();
print('email send');
}
i would like to see an email appear in my inbox with the written message of the user in there.
so, it seems like you should create an app password of the desired account.
you can ollow this link https://support.google.com/accounts/answer/185833?hl=en to create an app password. use this password in conjunction with the email in the mailer implementation and everything should work!
I have .net user control which will send email on click of button. Now, in email I want to send swf file embeded into the email. following is the code. But it does not show swf file in email.
protected void btnSubmit_Click(object sender, EventArgs e)
{
string body = "Dear Balvignan Team,\r\n\r\n";
if (txtComment.Text != null)
{
body = body + "Comment: " + txtComment.Text;
}
body=body + "<object classid='clsid:D27CDB6E-AE6D-11cf-96B8-444553540000' ";
body=body + "codebase='http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,19,0' width='425' height='300' align='middle'>";
body=body+ "<param name='movie' value='http://mydomain.com/images/ecards/CardCreative629.swf' />";
body=body + "<param name='quality' value='high' />";
body=body + "<param name='wmode' value='opaque' />";
body = body + "<embed src='http://mydomain.com/images/ecards/CardCreative629.swf' width='425' height='300' align='middle' quality='high' pluginspage='http://www.macromedia.com/go/getflashplayer' type='application/x-shockwave-flash' wmode='opaque' ></embed>";
body = body + "</object>";
if (SendEmail(txtEmail.Text.Trim(), "Comment", body, true) == true)
{
lblContactAcknowledge.Text = "Thank You For <br />Submitting comment.";
lblContactAcknowledge.Visible = true;
PnlTalkToUs.Visible = false;
}
else
{
lblContactAcknowledge.Visible = false;
PnlTalkToUs.Visible = true;
}
}
SendEmail(string From, string Subject, string Message, bool IsHTML) is function which sends email.
That's because basically no email clients support Flash.
Here is a blog article covering this topic.
You can embed static images instead, and some clients (or webmail interfaces) allow animated ones aswell. But you should not expect a client to show flash content, and therefore shouldn't use it in emails either.