-
-
Save Yogendra0Sharma/0871b183b88701c98b8a703c0f4dbbed to your computer and use it in GitHub Desktop.
Asynchronous mail sending using Amazon SES
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/python | |
| # install boto using pip | |
| import types | |
| from threading import Thread | |
| from boto import ( | |
| ses, | |
| connect_s3 | |
| ) | |
| # Amazon AWS config and credentials | |
| DEFAULT_AWS_REGION = "eu-west-1" | |
| AWS_ACCESS_KEY = "<Your-AWS-access-key>" | |
| AWS_SECRET_KEY = "<Your-AWS-secret-key>" | |
| # create an connection for SES AWS service with default region | |
| ses_conn = ses.connect_to_region( | |
| DEFAULT_AWS_REGION, | |
| aws_access_key_id=AWS_ACCESS_KEY, | |
| aws_secret_access_key=AWS_SECRET_KEY | |
| ) | |
| def async(f): | |
| def wrapper(*args, **kwargs): | |
| thr = Thread(target=f, args=args, kwargs=kwargs) | |
| thr.start() | |
| return wrapper | |
| @async | |
| def send_email(_from, to, subject, body): | |
| """Function to send email through Amazon AWS SES service | |
| :param _from: a source email | |
| :param to: a list of recipients or a single email of recipient | |
| :param subject: a subject text | |
| :param body: a body text or html | |
| :return: None | |
| """ | |
| recipients = [] | |
| # if a single recipient | |
| if isinstance(to, types.StringTypes): | |
| recipients.append(to) | |
| else: | |
| recipients = to | |
| try: | |
| # send mail | |
| ses_conn.send_email( | |
| source=_from, | |
| subject=subject, | |
| body=body, | |
| to_addresses=recipients, | |
| format='html' | |
| ) | |
| print "Email sent successfully to %s" % recipients | |
| except Exception as e: | |
| raise Exception("Problem in sending email :: %s" % str(e)) | |
| if __name__ == '__main__': | |
| # to send email one recipient | |
| send_email("noreply@testing.com", | |
| "user@testing.com", | |
| "Test Async Mail", | |
| "Hi, I am tesing this gist.") | |
| # to send email multiple recipients | |
| send_email("noreply@testing.com", | |
| ["user1@testing.com", "user2@testing.com"], | |
| "Test Async Mail", | |
| "Hi, I am tesing this gist.") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment