Send email with attachments on your google compute engine via sendgrid-python

precondition:
  1. Use the Google Cloud Launcher to sign up for the SendGrid Email service. Make a note of your SendGrid SMTP account credentials, which include username, password, and hostname. Your SMTP username and password are the same as what you used to sign up for the service. The SendGrid hostname is smtp.sendgrid.net.
  2. Create an API key:
    1. Sign in to Sendgrid and go to Settings > API Keys.
    2. Create an API key.
    3. Select the permissions for the key. At a minimum, the key will need Mail send permissions to send email.
    4. Click Save to create the key.
    5. SendGrid generates a new key. This is the only copy of the key so make sure to copy the key and save it for later.


 
Please remember your key and save it somewhere safe.
 
OK. Now we can use sendgrid python library to send email.
Of cause, you can still follow offical help to use sendgrid with other solution.
https://cloud.google.com/compute/docs/tutorials/sending-mail/using-sendgrid

install sendgrid-python 
$pip install sendgrid
 
Sample python codes:
errong_leng@blogvpn:~/algo$ cat sendmail.py
import base64
import getopt
import mimetypes
import os
import sendgrid
import sys
from sendgrid.helpers.mail import *

def useage():
    print ("python sendmail.py [-s subject] [-a attachment ] [-c cc-addr] [-b bcc-addr] [-f from-addr] [-t to-addr] to-addr . . .")
    sys.exit()

opts, args = getopt.getopt(sys.argv[1:], "ha:b:c:f:s:t:")

attachs = []
cc = []
bc = []
tc = []
from_addr = ''
subject = ''

for op, value in opts:
  if op == "-h":
      useage()
  elif op == "-a":
      attachs.append(value)
  elif op == "-b":
      bc.append(value)
  elif op == "-c":
      cc.append(value)
  elif op == "-s":
      subject = value
  elif op == "-f":
      from_addr = value
  elif op == "-t":
      tc.append(value)

if (len(args) <= 0):
    useage()

sg = sendgrid.SendGridAPIClient(apikey='REPLACEWITHYOURAPIKEY')
mail = Mail()
mail.from_email = (Email(from_addr))
mail.subject = subject
personalization = Personalization()
personalization.add_to(Email(args[0]))
for tcs in tc:
    personalization.add_to(Email(tcs))
for ccs in cc:
    personalization.add_cc(Email(ccs))
for bcc in bc:
    personalization.add_bcc(Email(bcc))
personalization.subject = subject
mail.add_personalization(personalization)

contents = args[1:]
for ct in contents:
    if (len(ct) > 0):
        mail.add_content(Content("text/plain", ct))
      
for af in attachs:
    data = ''
    with open(af, 'rb') as f:
        data = f.read()
        f.close()
    if (len(data) > 0):
        adata = base64.b64encode(data)
        attachment = Attachment()
        attachment.content = adata
        s = os.path.split(af)
        attachment.filename = s[len(s)-1]
        attachment.type = mimetypes.guess_type(attachment.filename)[0]
        attachment.disposition = "attachment"
        attachment.content_id = af
        mail.add_attachment(attachment)

response = sg.client.mail.send.post(request_body=mail.get())

print(response.status_code)
print(response.body)
print(response.headers)            
 
 
errong_leng@blogvpn:~/algo$ python sendmail.py -t "errong.leng@abc.com" -s 
"Hello" -f "errong.leng@gmail.com" -c "errong.leng@hotmail.com" 
-b "errong.leng@samsung.com" -a configs/104.199.178.17/zqzz.p12 
-a configs/104.199.178.17/zqzz.mobileconfig 
errong.leng@gmail.com "Hello with content and attachment" 
 
202

Server: nginx
Date: Fri, 19 May 2017 04:04:45 GMT
Content-Type: text/plain; charset=utf-8
Content-Length: 0
Connection: close
X-Message-Id: x7xHfWk8SmWlxUe6Ew6tmA
X-Frame-Options: DENY
Access-Control-Allow-Origin: https://sendgrid.api-docs.io
Access-Control-Allow-Methods: POST
Access-Control-Allow-Headers: Authorization, Content-Type, On-behalf-of, x-sg-elas-acl
Access-Control-Max-Age: 600
X-No-CORS-Reason: https://sendgrid.com/docs/Classroom/Basics/API/cors.html
 
Once you see 202, which means email sending successfully. 
 
 
 

Comments

Popular posts from this blog

How to fix error : no module named sendgrid when try to use sendgrid python lib in PHP.

react-native run-android : sun.security.provider.cert path.SunCertPathBuilderException : unable to find valid certification path to req uested target

react-native run-android : do not build/update modified code(App.js)