How can I send Email from gmail to another email account - dart

I think that this's an issue many coders are facing at the moment.
So let's find a solution:
I already tried ->
mailer2: ^1.2.5
var options = GmailSmtpOptions()
..username = ''
..password = '';
var emailTransport = SmtpTransport(options);
var envelope = Envelope()
..from = ''
..recipients.add(email)
..subject = ''
..html = "<h1>Title </h1>\n\n"
emailTransport.send(envelope)
.then((envelope) => print('Email sent!'))
.catchError((e) => print('Error occurred: $e'));
but the following error message came up:
Unsupported operation: Platform._localHostname
at Object.throw_ [as throw] (http://localhost:63913/dart_sdk.js:4463:11)
at Function._localHostname (http://localhost:63913/dart_sdk.js:54754:17)
at Function.get localHostname [as localHostname] (http://localhost:63913/dart_sdk.js:54810:33)
at get _localHostname (http://localhost:63913/dart_sdk.js:54713:27)
at Function.desc.get [as _localHostname] (http://localhost:63913/dart_sdk.js:4944:15)
at Function.get localHostname [as localHostname] (http://localhost:63913/dart_sdk.js:54666:26)
at mailer.GmailSmtpOptions.new.mailer.SmtpOptions.new
(http://localhost:63913/packages/mailer2/mailer.dart.lib.js:1178:30)
at new mailer.GmailSmtpOptions.new (http://localhost:63913/packages/mailer2/mailer.dart.lib.js:1229:43)
at http://localhost:63913/packages/bestbite_native/web/screens/screen_after_order.dart.lib.js:12394:37
at Generator.next (<anonymous>)
at runBody (http://localhost:63913/dart_sdk.js:37195:34)
at Object._async [as async] (http://localhost:63913/dart_sdk.js:37226:7)
at http://localhost:63913/packages/bestbite_native/web/screens/screen_after_order.dart.lib.js:12392:389
at _RootZone.runUnary (http://localhost:63913/dart_sdk.js:37029:58)
at _FutureListener.then.handleValue (http://localhost:63913/dart_sdk.js:32116:29)
at handleValueCallback (http://localhost:63913/dart_sdk.js:32663:49)
at Function._propagateToListeners (http://localhost:63913/dart_sdk.js:32701:17)
at _Future.new.[_completeWithValue] (http://localhost:63913/dart_sdk.js:32544:23)
at async._AsyncCallbackEntry.new.callback (http://localhost:63913/dart_sdk.js:32566:35)
at Object._microtaskLoop (http://localhost:63913/dart_sdk.js:37290:13)
at _startMicrotaskLoop (http://localhost:63913/dart_sdk.js:37296:13)
at http://localhost:63913/dart_sdk.js:32918:9Error: Unsupported operation: Platform._localHostname
Does anybody has an idea how to send emails in flutter web applications?
(Without opening an email tab)

"mailer2"(and the original package "mailer") imports dart:io which is not available on flutter web and therefore you cannot use this package.
A solution I have used in the past for sending emails is to create an http-triggered cloud function(e.g. Firebase functions, AWS Lambda, netlify functions) that sends the email. You can pass any data you need through the http request and have the cloud function send the email through something like nodemailer in Node.js.
There also may be other services or APIs available that already do what the cloud function does, though I have not seen many and they are not my preferred method

Related

Keep getting thrown Error: Username/Password required

Good afternoon,
Trying to create an SMS booking bot and am running into an issue trying to call the main.js file I have in .src and I'm a bit lost on why.
I have my .env file formatted as needed
node src/main.js
>main.js<
require("dotenv").config();
const from = process.env.PHONE_NUMBER
const to = process.env.MY_NUMBER
const twilio = require('twilio')();
process.env.TOKEN_SID,
process.env.TOKEN_SECRET,
{
accountSid: process.env.TOKEN_SID
}
;
twilio.messages.create({
from,
to,
body: "Hello from Twilio!"
})
.then(message => console.log('Message sent with SID ${message.sid}'))
.catch(error => console.error(error));
>Error output<:
Error: username is required
at new Twilio (/Users/*/Twilio/sms-booking/backend/node_modules/twilio/lib/rest/Twilio.js:139:11)
at initializer (/Users/*/Twilio/sms-booking/backend/node_modules/twilio/lib/index.js:10:10)
at Object.<anonymous> (/Users/*/Twilio/sms-booking/backend/src/main.js:6:33)
Error: Password is required
at new Twilio (/Users/*/Twilio/sms-booking/backend/node_modules/twilio/lib/rest/Twilio.js:139:11)
at initializer (/Users/*/Twilio/sms-booking/backend/node_modules/twilio/lib/index.js:10:10)
at Object.<anonymous> (/Users/*/Twilio/sms-booking/backend/src/main.js:6:33)

Method for invoking transaction from another transaction in Hyperledge composer

The old version of hyperledger support below method. But newest not
const generateReport = getFactory().newTransaction('org.cusat.hospital', 'GenerateReport');
While testing in new version shows an error of
Error: No valid responses from any peers. Response from attempted peer comms was an error: Error: transaction returned with failure: TypeError: getFactory(...).newTransaction is not a function
Please suggest alternative method.
i found one way of invoking transaction from java script. see if this helps.
const TransactionSubmit = require('composer-cli').Transaction.Submit;
let options = {
card: 'admin#tutorial-network',
data: '{"$class":"net.biz.digitalPropertyNetwork.RegisterPropertyForSale","transactionId":"TRANSACTION_001","seller":"mae#biznet.org","title":"TITLE_001"}'
};
TransactionSubmit.handler(options);

Azure IoT Device: Type error in client.js

I try to get an ARM device connected to Azure IoT Hub. I chose Node.js and got some sample code to get the device connected. I added the required NPM packages such as azure_iot_device, azure_iot_common, azure_iot_http_base.
Within the code, there is one line of code which causes an error.
The line: client.sendEvent(message, printResultFor('send'));
After this, on the debugging console I get the message:
\NodejsWebApp1\node_modules\azure-iot-device\lib\client.js:596
return new Client(new transportCtor(authenticationProvider), null, new blob_upload_1.BlobUploadClient(authenticationProvider));
^
TypeError: transportCtor is not a function
at Function.Client.fromConnectionString
(C:\Users\InterestedGuy\source\repos\NodejsWebApp1\NodejsWebApp1\node_modules\azure-iot-device\lib\client.js:596:27)
at sendmsg (C:\Users\InterestedGuy\source\repos\NodejsWebApp1\NodejsWebApp1\server.js:123:32)
at Server. (C:\Users\InterestedGuy\source\repos\NodejsWebApp1\NodejsWebApp1\server.js:48:9)
at emitTwo (events.js:87:13)
at Server.emit (events.js:172:7)
at HTTPParser.parserOnIncoming [as onIncoming] (_http_server.js:529:12)
at HTTPParser.parserOnHeadersComplete (_http_common.js:88:23)
Press any key to continue...
First guess was that I miss a library so I simply searched the Web where transportCtor should have been defined - but no success.
So the easy question is: where should this function be defined? I would expect the function is part of the Azure IoT SDK but I could not find it. Since the module client.js from azure_iot_device is reporting the error I expect it somewhere within the SDK - but where?
THX for any advice
You should install azure-iot-device-http package to communicate with Azure IoT Hub from any device over HTTP 1.1. You can use this command to get the latest version.
npm install -g azure-iot-device-http#latest
Following code is a tutorial shows how to use this package.
var clientFromConnectionString = require('azure-iot-device-http').clientFromConnectionString;
var Message = require('azure-iot-device').Message;
var connectionString = '[IoT Hub device connection string]';
var client = clientFromConnectionString(connectionString);
var connectCallback = function (err) {
if (err) {
console.error('Could not connect: ' + err);
} else {
console.log('Client connected');
var message = new Message('some data from my device');
client.sendEvent(message, function (err) {
if (err) console.log(err.toString());
});
client.on('message', function (msg) {
console.log(msg);
client.complete(msg, function () {
console.log('completed');
});
});
}
};
client.open(connectCallback);
BTW,for this tutorial you also need to install azure-iot-device package.

Twilio IP messaging set up with JS SDK

I'm having some serious troubles setting up IPMessaging services with Twilio.
I've set up the backend (PHP) for user authentication. I'm able to generate a Token with the Twillio Library.
I've also set up the user related APIs, in order to create/update/delete users for the Chat Service from the backend. I had to do this with curl however, because the library kept returning fatal errors, even if I downloaded the PHP SDK via composer and simply copy/pasted the docs examples.
I've finally got to the point in which I can create users via the backend, and then create tokens with the ServiceSId, user Identity and deviceId.
On the JS client side it's again impossible to set up the service, as following the Docs results in multiple errors.
I have first included the JS SDK from Twilio CDN (same v. of the docs).
I have then tried to initialize the client as so:
var token = gottenFromOurAPI;
var chatClient = new Twilio.Chat.Client(token);
chatClient.initiazlie()
.then(testchat);
function testchat(){ };
(as explained here: https://www.twilio.com/docs/api/chat/guides/initializing-sdk-clients)
I get this in the console:
angular.js:13920 chatClient: t {_events: Object, _maxListeners: undefined, _config: e, _channelsPromise: Promise, _channels: t…}
angular.js:13920 TypeError: chatClient.getChannels is not a function
at testchat (supportchat.controller.js:33)
at processQueue (angular.js:16383)
at angular.js:16399
at Scope.$eval (angular.js:17682)
at Scope.$digest (angular.js:17495)
at Scope.$apply (angular.js:17790)
at done (angular.js:11831)
at completeRequest (angular.js:12033)
at XMLHttpRequest.requestLoaded (angular.js:11966)(anonymous function) # angular.js:13920(anonymous function) # angular.js:10467processQueue # angular.js:16391(anonymous function) # angular.js:16399$eval # angular.js:17682$digest # angular.js:17495$apply # angular.js:17790done # angular.js:11831completeRequest # angular.js:12033requestLoaded # angular.js:11966
twilio-chat.min.js:246 POST https://cds.twilio.com/v3/Lists 401 (Unauthorized)(anonymous function) # twilio-chat.min.js:246t # twilio-chat.min.js:196s # twilio-chat.min.js:246p.post # twilio-chat.min.js:246f.post # twilio-chat.min.js:246value # twilio-chat.min.js:245value # twilio-chat.min.js:244(anonymous function) # twilio-chat.min.js:244
twilio-chat.min.js:150 Chat E: Failed to create session Objectbody: Objectdescription: "Unauthorized"headers: ObjectContent-Type: "application/json"Twilio-Request-Id: "RQb761bc6d95034e23b4ba244e965334d4"__proto__: Objectstatus: 401__proto__: Objectvalue # twilio-chat.min.js:150(anonymous function) # twilio-chat.min.js:150
:3000/#/dashboard:1 Uncaught (in promise) Object {status: 401, description: "Unauthorized", headers: Object, body: Object}
:3000/#/dashboard:1 Uncaught (in promise) Objectbody: Objectdescription: "Unauthorized"headers: Objectstatus: 401__proto__: Object
:3000/#/dashboard:1 Uncaught (in promise) Objectbody: Objectdescription: "Unauthorized"headers: Objectstatus: 401__proto__: Object
Since I'm having so many troubles simply setting up the thing, any advices on alternative (better) services?
 EDIT - PHP CODE FOR TOKEN CREATION
$endpointId = $this->idService . ':' . $this->idUser . ':' . $this->idDevice;
// Create access token, which we will serialize and send to the client
$token = new AccessToken(
TWILIO_ACCOUNT_SID,
TWILIO_API_KEY,
TWILIO_API_SECRET,
3600,
$this->idUser
);
// Grant access to IP Messaging
$grant = new IpMessagingGrant();
$grant->setServiceSid($TWILIO_IPM_SERVICE_SID);
$grant->setEndpointId($endpointId);
$token->addGrant($grant);
// return serialized token and the user's randomly generated ID
$tokenArr = [
'identity' => $this->idUser,
'token' => $token->toJWT(),
];
return $tokenArr;

Gmail API - unable to fetch messages from users in domain using google.auth.jwt

I am trying to fetch all emails under our company domain. I am using Node.js client library. In my last approach I used Oauth method as documented in quickstart guide. It was suggested that I should use JWT to authorize, but I am still unable to figure out how to do it properly in node (due to lack of documentation). This is my code:
var google = require('googleapis'),
gmail = google.gmail('v1');
var key = require('./service_key.json');
var jwtClient = new google.auth.JWT(
key.client_email,
null,
key.private_key,
['https://mail.google.com/','https://www.googleapis.com/auth/admin.directory.group']
);
jwtClient.authorize(function(err, tokens) {
if (err) {
console.log(err);
return;
}
gmail.users.messages.list({userId: 'me', auth: jwtClient}, (err, response)=>{
if (err) {
console.log(err);
return;
}
console.log(response);
});//messages.list
});//jwtClient.authorize
I get error :
{ Error: Bad Request
at Request._callback (/home/kunok/code/gapi/node_modules/google-auth-library/lib/transporters.js:85:15)
at Request.self.callback (/home/kunok/code/gapi/node_modules/google-auth-library/node_modules/request/request.js:198:22)
at emitTwo (events.js:106:13)
at Request.emit (events.js:191:7)
at Request.<anonymous> (/home/kunok/code/gapi/node_modules/google-auth-library/node_modules/request/request.js:1057:14)
at emitOne (events.js:101:20)
at Request.emit (events.js:188:7)
at IncomingMessage.<anonymous> (/home/kunok/code/gapi/node_modules/google-auth-library/node_modules/request/request.js:1003:12)
at emitNone (events.js:91:20)
at IncomingMessage.emit (events.js:185:7)
code: 400,
errors:
[ { domain: 'global',
reason: 'failedPrecondition',
message: 'Bad Request' } ] }
I am unable to understand the right approach. I want to skip any user interaction and fetch all mails under domain by running CRON job node.js scripts from the server. I have all admin rights. What is wrong in my approach?
Try changing your jwt format to
var jwt = new googleapis.auth.JWT(
SERVICE_ACCOUNT_EMAIL,
SERVICE_ACCOUNT_KEY_FILE,
null,
['https://www.googleapis.com/auth/admin.directory.group'],
account_with_Admin_SDK_access_to_impersonate#example.com
);
Based from Perform Google Apps Domain-Wide Delegation of Authority code sample(python):
"""Build and returns an Admin SDK Directory service object authorized with the service accounts
that act on behalf of the given user.
Args:
user_email: The email of the user. Needs permissions to access the Admin APIs.
Returns:
Admin SDK directory service object.
"""
credentials = ServiceAccountCredentials.from_p12_keyfile(
SERVICE_ACCOUNT_EMAIL,
SERVICE_ACCOUNT_PKCS12_FILE_PATH,
'notasecret',
scopes=['https://www.googleapis.com/auth/admin.directory.user'])
credentials = credentials.create_delegated(user_email)
Hope this helps!

Resources