How to only open email app and attach a file? - flutter

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

Related

add image in email with flutter_email_sender

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,
);

Ionic SocialSharing with pdf file for whatsapp

I am using pdfMaker to create an object of type Document, I would like to send this file to a contact I have saved on Whatsapp, it would be something similar to using the shareViaWhatsAppToReceiver function using SocialSharing.
The file's attachment would already come in the message.
this.socialSharing.shareViaWhatsAppToReceiver(`+55 ${contact.phone}`, `PDF`,
null, this.pdfObj).then(async () => {
const toast = await this._toast.create({
message: 'Send success.',
duration: 3000
});
});
The way I am doing above does not work, I would like to send the document directly as a parameter so that the message on Whatsapp is attached.

Flutter open whatsapp with text message

I want to open whatsapp from my Flutter application and send a specific text string. I'll select who I send it to when I'm in whatsapp.
After making some research I came up with this:
_launchWhatsapp() async {
const url = "https://wa.me/?text=Hey buddy, try this super cool new app!";
if (await canLaunch(url)) {
await launch(url);
} else {
throw 'Could not launch $url';
}
}
Which works ok ish, however there are two problems:
As soon as I make the text string into multi words it fails. So if I change it to:
_launchWhatsapp() async {
const url = "https://wa.me/?text=Hey buddy, try this super cool new app!";
if (await canLaunch(url)) {
await launch(url);
} else {
throw 'Could not launch $url';
}
}
Then the Could not launch $url is thrown.
I have whatsapp already installed on my phone, but it doesn't go directly to the app, instead it gives me a webpage first and the option to open the app.
Here is the webpage that I see:
Any help on resolving either of these issues would be greatly appreciated.
Thanks
Carson
P.s. I'm using the Url_launcher package to do this.
From the official Whatsapp FAQ, you can see that using "Universal links are the preferred method of linking to a WhatsApp account".
So in your code, the url string should be:
const url = "https://wa.me/?text=YourTextHere";
If the user has Whatsapp installed in his phone, this link will open it directly. That should solve the problem of opening a webpage first.
For the problem of not being able to send multi-word messages, that's because you need to encode your message as a URL. Thats stated in the documentation aswell:
URL-encodedtext is the URL-encoded pre-filled message.
So, in order to url-encode your message in Dart, you can do it as follows:
const url = "https://wa.me/?text=Your Message here";
var encoded = Uri.encodeFull(url);
As seen in the Dart Language tour.
Please note that in your example-code you have put an extra set of single quotes around the text-message, which you shouldn't.
Edit:
Another option also presented in the Whatsapp FAQ is to directly use the Whatsapp Scheme. If you want to try that, you can use the following url:
const url = "whatsapp://send?text=Hello World!"
Please also note that if you are testing in iOS9 or greater, the Apple Documentation states:
Important
If your app is linked on or after iOS 9.0, you must declare the URL schemes you pass to this method by adding the LSApplicationQueriesSchemes key to your app's Info.plist file. This method always returns false for undeclared schemes, whether or not an appropriate app is installed. To learn more about the key, see LSApplicationQueriesSchemes.
So you need to add the following keys to your info.plist, in case you are using the custom whatsapp scheme:
<key>LSApplicationQueriesSchemes</key>
<array>
<string>whatsapp</string>
</array>
till date: 27-06-2022
using package: https://pub.dev/packages/url_launcher
dependencies - url_launcher: ^6.1.2
TextButton(
onPressed: () {
_launchWhatsapp();
},
)
_launchWhatsapp() async {
var whatsapp = "+91XXXXXXXXXX";
var whatsappAndroid =Uri.parse("whatsapp://send?phone=$whatsapp&text=hello");
if (await canLaunchUrl(whatsappAndroid)) {
await launchUrl(whatsappAndroid);
} else {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text("WhatsApp is not installed on the device"),
),
);
}
}
Here is new update way...
whatsapp() async{
var contact = "+880123232333";
var androidUrl = "whatsapp://send?phone=$contact&text=Hi, I need some help";
var iosUrl = "https://wa.me/$contact?text=${Uri.parse('Hi, I need some help')}";
try{
if(Platform.isIOS){
await launchUrl(Uri.parse(iosUrl));
}
else{
await launchUrl(Uri.parse(androidUrl));
}
} on Exception{
EasyLoading.showError('WhatsApp is not installed.');
}
}
and call whatsapp function in onpress or ontap function
For using the wa.me domain, make sure to use this format...
https://wa.me/123?text=Your Message here
This will send to the phone number 123. Otherwise, you will get an error message (see? https://wa.me/?text=YourMessageHere ). Or, if you don't want to include the phone number, try this...
https://api.whatsapp.com/send?text=Hello there!
Remember, wa.me requires a phone number, whereas api.whatsapp.com does not. Hope this helps!
I know it is too late for answering this, but for those who want the same functionality, the current way is to do it like this:
launchUrl(Uri.parse('https://wa.me/$countryCode$contactNo?text=Hi'),
mode: LaunchMode.externalApplication);
if you will use URL Launcher then the whatsapp link will be open on web browser. So you need to set parameter - not to open on safari browser. The complete code you can find on this flutter tutorial.
But for your case use below code.
await launch(whatappURL, forceSafariVC: false);
Today i am adding solution its working fine on my desktop and phone
Add 91 if your country code is +91
Remember not add any http or https prefix otherwise wont work.
whatsapp://send?phone=9112345678&text=Hello%20World!

Send email from Contact form directly without opening gmail application

I want to send email directly to admin email without opening gmail application through URL package in flutter URL package work perfectly but that is not required. I want to do it through fire-base where I also want to save all data send to admin email. I need to know the email function of firebase or any such function that help me to send direct email.
_launchURL(String toMailId, String subject, String body) async {
var url = 'mailto:$toMailId?subject=$subject&body=$body';
if (await canLaunch(url)) {
await launch(url);
} else {
throw 'Could not launch $url';
}
}

Flutter (mailer package): mailing from within the app. not receiving mail

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!