Sending emails using loopback email connector - loopbackjs

I am trying to use loopback-email-connector to send emails. I want to setup 2 email accounts. I am doing the following in datasources.json.
"emails": {
"name": "emails",
"connector": "mail",
"transports": [
{
"type": "smtp",
"host": "smtp.yandex.com",
"secure": true,
"port": 465,
"tls": {
"rejectUnauthorized": false
},
"auth": {
"user": "a1#abc.com",
"pass": "password"
}
},
{
"type": "smtp",
"host": "smtp.yandex.com",
"secure": true,
"port": 465,
"tls": {
"rejectUnauthorized": false
},
"auth": {
"user": "a2#abc.com",
"pass": "password"
}
}
]
}
In above case I have added 2 email accounts - a1#abc.com and a2#abc.com.
To send email, I am doing the following:
app.models.Email.send({
to: 'foo#bar.com',
from: 'a1#abc.com',
subject: 'my subject',
text: 'my text',
html: 'my <em>html</em>'
}, function(err, mail) {
console.log('email sent!');
cb(err);
});
This is successfully sending the email. But if I use from email as a2#abc.com, it doesn't work. I get the following error:
Error: Mail command failed: 553 5.7.1 Sender address rejected: not owned by auth user.
But if I move, a2#abc.com as the first email in datasources.json, it works.
In fact, which ever email comes first in the datasources.json only that works, the second one is not working. How can i setup multiple email ids in this case?

I was able to figure out a way which does not involve creating multiple datasources for each email.
Setting alias for each transport assigns an alias which can be used while sending emails. In respect to the above question, we can do something like below:
"emails": {
"name": "emails",
"connector": "mail",
"transports": [
{
"type": "smtp",
"host": "smtp.yandex.com",
"secure": true,
"port": 465,
"alias": "a1",
"tls": {
"rejectUnauthorized": false
},
"auth": {
"user": "a1#abc.com",
"pass": "password"
}
},
{
"type": "smtp",
"host": "smtp.yandex.com",
"secure": true,
"port": 465,
"alias": "a2",
"tls": {
"rejectUnauthorized": false
},
"auth": {
"user": "a2#abc.com",
"pass": "password"
}
}
]
}
After setting the alias as above, to send email, we can use the alias as transport.
app.models.Email.send({
to: 'foo#bar.com',
from: 'a1#abc.com',
subject: 'my subject',
text: 'my text',
html: 'my <em>html</em>',
transport: "a1"
}, function(err, mail) {
console.log('email sent!');
cb(err);
});
In the above example, I have set a1 alias and am sending email by setting transport as a1. This works fine.

The mail server is rejecting your email because you're trying to send a mail which is not same with your email option.
Just try to update a1#abc.com with your mail a2#abc.com like following:-
app.models.Email.send({
to: 'foo#bar.com',
from: 'a2#abc.com',
subject: 'my subject',
text: 'my text',
html: 'my <em>html</em>'
}, function(err, mail) {
console.log('email sent!');
cb(err);
});
You have to keep same email ids in your transports config and "from-to" email.

Please go through following steps:
1)Create 2 different datasource, with a different name and add single emailId to each. One datasource you have already made, from that just remove one emailId and attach to another one.
2)Create a new model(Ex. TestMail) by command lb model, set one datasource you want to attach with for sending mail.
3)Now you have two models, one Email and other TestMail, now just use send() with your required mail model.
This worked for me!

Related

Stripe Webhook does not work when I changed it to my domain and https

I'm trying to configure Django App with Stripe.
Webhook works well When setting the Endpoint URL using "IP address" and "http".
Here is the Endpoint URL.
http://3.129.xx.xxx/subscriptions/webhook/
But when I changed it to my domain and add "https", It does not work.
Here is the Endpoint URL with my domain.
https://mysite12345.com/subscriptions/webhook/
1.HTTP statas code is "time out".
2.Event type is "checkout.session.completed"
3.The log is "200 OK" but "Webhook event" is failed, it retries again and again but still failed.
4.Of course, the domain is valid(I can access other pages)
5.SSL certificate is issued by AWS.
6.Testing endpoint just manually do a POST request, it says.
KeyError at /subscriptions/webhook/
'HTTP_STRIPE_SIGNATURE'
Request Method: GET
Request URL: http://mysite12345.com/subscriptions/webhook/
Django Version: 3.2.4
Exception Type: KeyError
Exception Value:
'HTTP_STRIPE_SIGNATURE'
Exception Location: /home/app_admin/venv_ruling/ruling/subscriptions/views.py, line 103, in stripe_webhook
Python Executable: /home/app_admin/venv_ruling/bin/python3
Python Version: 3.7.8
Python Path:
['/home/app_admin/venv_ruling/ruling',
'/usr/lib64/python37.zip',
'/usr/lib64/python3.7',
'/usr/lib64/python3.7/lib-dynload',
'/home/app_admin/venv_ruling/lib64/python3.7/site-packages',
'/home/app_admin/venv_ruling/lib/python3.7/site-packages']
In "Request URL:" it says "http" not "https" I also wonder if it's OK.
7.Below is request for Endpoint
{
"id": "evt_1JFX0XJvSJBZN02KlqeHjJWi",
"object": "event",
"api_version": "2020-08-27",
"created": 1626841569,
"data": {
"object": {
"id": "cs_test_a1VJ8H3hotDNG0bw8q583Q4r86u5J7Q0ZC4lrmCjXwwdNYE866YJiOmcza",
"object": "checkout.session",
"allow_promotion_codes": null,
"amount_subtotal": 3900,
"amount_total": 3900,
"automatic_tax": {
"enabled": false,
"status": null
},
"billing_address_collection": null,
"cancel_url": "https://mysite12345.com/subscriptions/cancel/",
"client_reference_id": "1",
"currency": "usd",
"customer": "cus_JtJdr9wDqNEdBf",
"customer_details": {
"email": "myemail#gmail.com",
"tax_exempt": "none",
"tax_ids": [
]
},
"customer_email": null,
"livemode": false,
"locale": null,
"metadata": {
},
"mode": "subscription",
"payment_intent": null,
"payment_method_options": {
},
"payment_method_types": [
"card"
],
"payment_status": "paid",
"setup_intent": null,
"shipping": null,
"shipping_address_collection": null,
"submit_type": null,
"subscription": "sub_JtJdTWtjY315lM",
"success_url": "https://mysite12345.com/subscriptions/success?session_id={CHECKOUT_SESSION_ID}",
"total_details": {
"amount_discount": 0,
"amount_shipping": 0,
"amount_tax": 0
},
"url": null
}
},
"livemode": false,
"pending_webhooks": 1,
"request": {
"id": "req_NX2udo8Xr4P94W",
"idempotency_key": null
},
"type": "checkout.session.completed"
}
I wonder why IP address and "http" Endpoint URL works well but a domain name and "https" do not.
When I changed "http" to "https" do I need to adjust something or am I missing something?
I just mentioned the above settings in this question but still if more code is required then tell me I'll update my question with that information.
Thank you

How can I un-spam my domain while testing mailgun webhooks?

I managed to create all that code that creates mailgun webhooks plus many other things like record responses to local database.
During my tests I send emails to yahoo & gmail and of course - as you expected - I pressed a couple of times the spam button at my tablet's yahoo app to test and verify the events recorded with my code.
My problem is that now when I send to that yahoo address from the domain under test the email never reaches my inbox and at the logs I read:
4.7.0 [TSS04] Messages from 159.135.140.82 temporarily deferred due to user complaints - 4.16.55.1; see https://postmaster.verizonmedia.com/error-codes
See what mailgun reports:
{
"severity": "temporary",
"tags": [
"issue 1",
"newsletter",
"2020"
],
"mailing-list": {
"list-id": "xyz101.mail.mysite.com",
"sid": "1634752",
"address": "xyz101#mail.mysite.com"
},
"storage": {
"url": "https://storage.eu.mailgun.net/v3/domains/mail.mysite.com/messages/AgEFucSTB0eaifXAHzlNKbRoSH0IddfpZA==",
"key": "AgEFucSTB0eaifXAHzlNKbRoSH0IddfpZA=="
},
"delivery-status": {
"tls": true,
"mx-host": "mx-eu.mail.am0.yahoodns.net",
"attempt-no": 1,
"description": "",
"session-seconds": 0.39575695991516113,
"retry-seconds": 600,
"code": 421,
"message": "4.7.0 [TSS04] Messages from 159.135.140.82 temporarily deferred due to user complaints - 4.16.55.1; see https://postmaster.verizonmedia.com/error-codes",
"certificate-verified": true
},
"recipient-domain": "yahoo.co.uk",
"id": "D5IqK77PRA29RvULyzXLsw",
"campaigns": [],
"reason": "generic",
"user-variables": {
"id": "15"
},
"flags": {
"is-routed": false,
"is-authenticated": true,
"is-system-test": false,
"is-test-mode": false
},
"log-level": "warn",
"timestamp": 1604915932.781863,
"envelope": {
"transport": "smtp",
"sender": "sales#mail.mysite.com",
"sending-ip": "159.135.140.82",
"targets": "blah-blah-blah#yahoo.co.uk"
},
"message": {
"headers": {
"to": "cent C. <blah-blah-blah#yahoo.co.uk>",
"message-id": "20201109095852.1.8EC4631A16DA1C10#mail.mysite.com",
"from": "mysite <sales#mail.mysite.com>",
"subject": "test_MailGunHttpClient_send_from_real_domain_with_tags_with_tracking_opens_and_clicks_with_unsubscribe_enabled_and_with_recipient_variables_visible_to_webhooks_to_mailing_list_of_access_type_readonly"
},
"attachments": [],
"size": 2130
},
"recipient": "blah-blah-blah#yahoo.co.uk",
"event": "failed"
}
This message eventually will become severity: "permanent".
Any idea how I can reverse this behavior at yahoo servers not accepting my emails(*)?
(*) For another domain I setup at Mailgun I inspect deliverability as I haven't clicked the spam button for emails landed from that domain
Looks like your actions have had some repercussions, emails from one of our accounts using the same IP are blocked by Yahoo, Aol etc. And it started for no reason related to us, the recipients or the content of the emails (it is a paid newsletter).

About "PUT" and "DELETE" query

I just started using loopback and I have 'Profile' model in which addresses are embedded
{
"addresses":
[{
"type": "office",
"street": "2",
"city": "Noida",
"state": "UP",
"country": "india",
"zipCode": "201301",
"id": "b6268532-96a9-427e-87a5-df04750af2a0"
},
{
"type": "home",
"street": "1",
"city": "Noida",
"state": "UP",
"country": "india",
"zipCode": "201301",
"id": "6812b958-afb2-4e91-bdde-0977545c2e46"
}
]
}
this is an array of address and i want to delete the record of "id:6812b958-afb2-4e91-bdde-0977545c2e46" and update the record of "id:b6268532-96a9-427e-87a5-df04750af2a0".
Used methods like destroyById, updateById,remove,updateAttributes and updateAll but nothing worked.
How can i perform this?
i am using loopback with mongodb.
code for delete
code for update
what is wrong in this code? and which other methods can be used instead?
Thankyou in advance.
Its very simple. You need to provide id with the url in 'delete' request.
For Example:
var req = url + "/" + id
//url is your loopback endpoint url like api/user
$.ajax({
type: 'delete',
contentType: "application/json",
contentLength: "0",
url: req,
//data: id,
traditional: true,
success: function (response) {
//your function after deleting record
}
});
Hope it works!

How do I config an Email datasource in LoopBack for AWS SES email service?

LoopBack instructions ask for an entry in the transports array of the datasources.json file.
AWS uses nodemailer instructions ask for an object to be created.
But you cannot create a JS object in a json file.
Here is my datasource.json file so far. How do I configure the awsEmail datasource for AWS SES?
...
"awsEmail": {
"name": "awsEmail",
"connector": "mail",
"transports": [
{
"type": "ses",
"host": "aws.amazon.com",
"secure": false,
"port": 587,
"tls": {
"rejectUnauthorized": false
},
"auth": {
"user": "my user name",
"pass": "my password"
}
}
]
}
...
Have you considered doing this with SMTP? The below works for me.
"awsEmail": {
"name": "awsEmail",
"connector": "mail",
"defaultForType": "mail",
"transports": [
{
"type": "SMTP",
"host": "email-smtp.us-east-1.amazonaws.com",
"secure": true,
"port": 465,
"auth": {
"user": "your smtp username",
"pass": "your smtp password"
}
}
]
}
"ses": {
"name": "ses",
"connector": "email",
"transports": [
{
"type": "ses",
"accessKeyId": "AWS accessKeyId",
"secretAccessKey": "AWS secretAccessKey",
"rateLimit": 1
}
]
}
This works for me.
you must first create Ses user via console or cli and then use this user in your code. The following is python code I used for lambda execution which will send the file from s3 to my email. Please note enter the corret user and pwd
ses_user = "AKIXXXXXXXXXXXXXXXXXXXXXX"
ses_pwd = "AiKxxxxxxxxxxxxxxxiiiiiiiiiiiixxxxxx"
def mail(fromadd,to, subject, text, attach):
msg = MIMEMultipart()
msg['From'] = fromadd
msg['To'] = to
msg['Subject'] = subject
msg.attach(MIMEText(text))
part = MIMEBase('application', 'octet-stream')
part.set_payload(open(attach, 'rb').read())
Encoders.encode_base64(part)
part.add_header('Content-Disposition','attachment; filename="%s"' % os.path.basename(attach))
msg.attach(part)
mailServer = smtplib.SMTP("email-smtp.us-east-1.amazonaws.com", 587)
mailServer.ehlo()
mailServer.starttls()
mailServer.ehlo()
mailServer.login(ses_user, ses_pwd)
mailServer.sendmail(fromadd, to, msg.as_string())
# Should be mailServer.quit(), but that crashes...
mailServer.close()
date_fmt = strftime("%Y_%m_%d", gmtime())
#Give your file path
filepath ='/tmp/filename_' + date_fmt + '.csv'
#Give your filename
mail("sender_email","reciepient_email",filepath)
s3.Object('bucket', filename).put(Body=open(filepath, 'rb'))

Test Slack team_join event with Postman

I've followed this Slack tutorial to create an onboarding bot that gives people a few tips on how to interaction with other members. The tutorial recommends using Postman to test onboard experience, but it's not clear on how. I'm getting stuck on this: where do I put the a authorization token?
Prereqs:
ngrok is running on port 9292
rackup was run to start the server
I followed all steps to configure the Slack app as shown in the tutorial
I clicked the Slack button to authorize the application
What I'm doing:
Using Postman macOS client to send this default JSON event for team_join to the /events endpoint:
{
"type": "team_join",
"user": {
"id": "U023BECGF",
"name": "bobby",
"deleted": false,
"color": "9f69e7",
"profile": {
"first_name": "Bobby",
"last_name": "Tables",
"real_name": "Bobby Tables",
"email": "bobby#slack.com"
},
"is_admin": true,
"is_owner": true,
"is_primary_owner": true,
"is_restricted": false,
"is_ultra_restricted": false,
"has_2fa": false,
"two_factor_type": "sms"
}
}
I've tried including token as a parameter, header key/value and within the JSON object. None of these approaches seems to do it and it results in an authorization error. I get Invalid Slack verification token received: or a parsing issue.
How does one test something like a new user joining using this setup?
The token is available within the Event envelope, so you'll need to go up one level in the JSON:
{
"token": "{{verification_token}}",
"team_id": "{{team_id}}",
"api_app_id": "{{app_id}}",
"event": {
"type": "team_join",
"user": {
"id": "{{user_id}}",
"team_id": "{{team_id}}",
"name": "{{user_name}}",
"deleted": false,
"status": null,
"real_name": "{{user_real_name}}",
"profile": {
"first_name": "{{user_first_name}}",
"last_name": "{{user_last_name}}",
"real_name": "{{user_real_name}}",
"real_name_normalized": "{{user_real_name}}"
},
"is_bot": false
}
},
"type": "event_callback",
"authed_users": ["{{authed_user}}"]
}