How to send emails from django shell with AWS ses? - django

I have verified my domain with AWS SES and as a result my site successfully does send password verification emails (via allauth).
I would, however, also like to be able to send emails based on local scripts. To do this I have been using django shell_plus:
from django.core.mail import send_mail
send_mail("It works!", "This will get sent through anymail",
"me#mysite.com", ["me#mysite.com"])
I get output of '1' suggesting this the email has been sent successfully but I do not receive an email
I think my config is correct given that the site does successfully send emails:
EMAIL_BACKEND = "anymail.backends.amazon_ses.EmailBackend"
ANYMAIL = {
"AMAZON_SES_CLIENT_PARAMS": {
"aws_access_key_id": AWS_ACCESS_KEY_ID,
"aws_secret_access_key": AWS_SECRET_ACCESS_KEY,
"region_name": "us-east-1",
},
}
Can anyone explain what I need to do to send emails from the terminal i.e. without being directly logged into an AWS server?

Was a basic error - I had the required settings in my production config file, but not in my dev config file

Related

Send emails by reading email address from S3

I am trying the following -
Read the email address from a csv file in S3, first column has email address, second column has the subject, third column has the body of the email.
Send email with the subject and body to the email address read from S3.
I was able to read the file in S3 into a DF using Lambda, but unable to send the email. Any ideas on how to do this using AWS services
you can use same lambda function to create smtp server of your own to send emails. e.g. while parsing data from the S3 csv file, for each entry in csv send email.
#!/usr/bin/env python
import smtplib
from email.mime.text import MIMEText
sender = 'xx#xx.com' # parsed data
receivers = ['yy#yy.com'] # parsed data
port = 1025
msg = MIMEText('email text') # parsed data
msg['Subject'] = 'Test mail'
msg['From'] = sender
msg['To'] = receivers
with smtplib.SMTP('localhost', port) as server:
server.sendmail(sender, receivers, msg.as_string())
print("email sent")
You can send emails from within a Lambda function by invoking the SES service. There is an example of creating a Lambda function (implemented in Java) that shows how to send an email message as part of a larger workflow created using AWS Step Functions. See this example:
Create AWS serverless workflows by using the AWS SDK for Java

Email not being sent / No errors AWS/SES

I have an AWS Lambda function:
sendEmail.js
const AWS = require('aws-sdk');
const ses = new AWS.SES();
function sendEmail(subject, message, senderEmail) {
const params = {
Destination: {
ToAddresses: [
process.env.VERIFIED_EMAIL
]
},
Message: {
Body: {
Text: {
Data: message,
Charset: 'UTF-8'
}
},
Subject: {
Data: subject,
Charset: 'UTF-8'
}
},
Source: process.env.VERIFIED_EMAIL,
ReplyToAddresses: [senderEmail]
}
return ses.sendEmail(params).promise();
}
module.exports = sendEmail;
Called from
index.js
const sendEmail = require('./sendEmail');
exports.handler = async (event, context) => {
return sendEmail(event.subject, event.message, event.email).then((response) => { context.done(null, 'Email sent')});
};
I have the env. variable VERIFIED_EMAIL set to a personal e-mail that is verified by AWS/SES.
My test case:
{
"email": "redacted#outlook.com",
"subject": "desc",
"message": "Hello!"
}
Which passes and returns "Email sent" but I don't actually receive an e-mail. I've also deployed the API-GATEWAY and I can call the API w/ Postman and I receive the same "Email sent" message but no e-mail is actually sent.
I don't think it should be an issue with being in sandbox mode because the email I am sending it from is verified.
PS:
When Looking at the SES management console it says that the emails are being sent (they take up part of the 200 daily quota) and then that none of them were bounced or rejected but simply deliveries.
A few things you should check with your SES before diving deeper.
In sandbox mode both "source email address" and "destination email address" have to be verified. Instead a mail won't be delivered.
In case you verify Email Domain so appropriate dns and DKIM records have to be added in your domain. Plus additional whitelist clearance is assumed if you use corporate domains.
Your IAM AWS user should be permitted to execute SES api calls. Check your policies and roles. Check Secret Key and Secret Id you use.
There might be problems when you use inappropriate email types and email sending endpoints (eg you try to send "SingleTemplatedMessage" via "BulkTemplatedMessage" endpoint)
Check all this things first.
Then you might try something else. In my project we use AWS SDK based on java to interact between BE and SES. It provides logs containing message statuses (if a message was sent successfully, rejected, its id and other errors if they occurred)
Additionally to keep track on every single message you send you can set up SES-SNS to exchange with notifications. It's described in the following article
https://sysgears.com/articles/how-to-track-email-status-with-amazon-ses-and-amazon-sns/
Other problems might occur in your mail client (spam filters etc)
Follow the check list to troubleshoot SES email sending:
Check the SMTP credential is ok or not using code shared by AWS
Same credential using in multiple application/IP may not work
Use minimum mail configuration, if you do not know setting value remove it, do not leave it with NULL.
Set, $config['charset'] = 'UTF-8'; // // 'UTF-8', 'ISO-8859-15'
Set, $config['newline'] = "\r\n"; // "\r\n" or "\n" or "\r"
Additional Check
Make sure trying to send email to the same domain if SES account is Sandbox
Check all outbound with mail TCP port is open
If using NATgateway Check both inbound and outbound with mail TCP port is open in open for the mail sending instance in it.

Does AWS SES work with grails Mail plugin 1.0.7?

I would like to use the AWS SES mail service using SMTP. I know it works for some versions, but I haven't gotten it to work for my application yet. I get a 530 Authentication error.
My question is in three parts:
1. Does AWS smtp work using Grails 2.3.1 with the Mail 1.0.7 plugin using java 1.7?
If it does work, how does one configure it?
If it does work, how can I get more debug information to figure what is wrong?
I've tried every configuration example variant I've come across for this. My latest is below. (It's clear I don't really understand the Mail plugin and the Java mail class, I'm just trying to suss out a working configuration incantation.)
Here is what I have in my config.groovy file:
grails {
mail {
host = 'email-smtp.us-east-1.amazonaws.com'
port = '587'
username = SMTP AWS username, not IAMS username
password= SMTP AWS password, not IAMS password
props = [ 'mail.debug': true,
'mail.smtp.host' : 'email-smtp.us-east-1.amazonaws.com',
'mail.smtp.auth': 'true',
'mail.smtp.starttls.enable': 'true',
'mail.smtp.port': '587',
'mail.smtp.starttls.required': 'true',
'mail.smtp.user' : smtp username from above,
'mail.smtp.usernme' : smtp username from above,
'mail.smtp.password': smtp password from above,
'mail.smtp.socketFactory.port': '587',
'mail.smtp.socketFactory.class':
'javax.net.ssl.SSLSocketFactory',
'mail.smtp.EnableSSL.enable':'true',
'mail.smtp.socketFactory.fallback': 'false' ]
}
}
I have successfully made direct AWS SES emails using the aws-sdk:1.9.40 plugin, by the way.
I am using the mailService.sendmail code from the Mail plugin. This is unchanged (beyond the hardcoded html text), and works fine when the configuration went to our email server.
def resp = mailService.sendMail {
from replyToEmail
replyTo replyToEmail
to user.email
subject emailSubject
html "This is the mesage text Mar 20"
}
Any help at all would be most appreciated!!

Anymail Mailgun Error

I am trying to integrate django-anymail with mailgun. When I send a mail with django send_mail as
send_mail('Testing', 'Test dsadsadsa asdsa body', 'xyz#mailinator.com', ['xxxx#gmail.com'])
It gives an error:
AnymailRequestsAPIError: Sending a message to xxxx#gmail.com from xyz#mailinator.com
ESP API response 404:
{
"message": "Domain not found: mailinator.com"
}
How can I get rid of this?
My settings file contains this:
ANYMAIL = {
"MAILGUN_API_KEY": "key-xxxmyprivatekey",
}
EMAIL_BACKEND = "anymail.backends.mailgun.MailgunBackend"
DEFAULT_FROM_EMAIL = "no-reply#mailinator.com"
It sounds like you have not verified your sending domain in Mailgun. Anymail is reporting the API error directly from your ESP, Mailgun, which is complaining they can't find the domain you're trying to send from.
Sign into your Mailgun account and check the domains list in their dashboard. Is mg.mailinator.com listed there with a green "Active" badge? If not, add it if necessary, and then follow Mailgun's instructions to verify the domain.

How can I get Django on Google App Engine to automatically email server 500 errors to Admins?

When my App raises a server 500 error, I'm not receiving the automatic Django email that it should be sending: https://docs.djangoproject.com/en/1.3/howto/error-reporting/
I'm using the Google App Engine Django Helper at http://code.google.com/p/google-app-engine-django/
In my settings.py file:
DEBUG = False
ADMINS = (('Support', 'Support#******.com'),)
EMAIL_HOST = ''
SERVER_EMAIL = 'Support#******.com'
In the Google App Engine Dashboard, I've added Support#**.com (The same email in my settings.py) to the admins with the role of Viewer. I've tried changing the role to Developer.
I think the problem is this line:
EMAIL_HOST = ''
Since the Django docs say
In order to send e-mail, Django
requires a few settings telling it how
to connect to your mail server. At the
very least, you’ll need to specify
EMAIL_HOST. . .
But, the there are comments in the settings.py file that came with the google-app-engine-django project that say
# Ensure that email is not sent via SMTP by default to match the standard App
# Engine SDK behaviour. If you want to send email via SMTP then add the name of
# your mailserver here.
EMAIL_HOST = ''
Make sure you specify the 'SERVER_EMAIL' (https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-SERVER_EMAIL) in your settings. Otherwise the emails will be sent from "root#localhost" and AppEngine won't send them.