Skip to content

Commit

Permalink
Merge pull request #11 from GDG-GANDHINAGAR/sendgrid
Browse files Browse the repository at this point in the history
Add Sendgrid way
  • Loading branch information
rossoskull authored Oct 11, 2019
2 parents 517f201 + 30c652e commit df61cb3
Show file tree
Hide file tree
Showing 7 changed files with 201 additions and 26 deletions.
1 change: 1 addition & 0 deletions Pipfile
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ google-auth-oauthlib = "*"
qrcode = "*"
python-dotenv = "*"
mailjet-rest = "*"
sendgrid = "*"

[requires]
python_version = "3.7"
19 changes: 18 additions & 1 deletion Pipfile.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 4 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,12 +40,13 @@ pipenv shell
Create a `.env` file in the root directory of your project, and add the following variables:

```env
MJ_APIKEY_PUBLIC=<YOUR-MAILJET-PUBLIC-KEY>
MJ_APIKEY_PRIVATE=<>YOUR-MAILJET-PRIVATE-KEY>
FONT=<FONT-FILE-NAME>
SHEET_ID=<YOUR-GOOGLE-SHEET-ID>
ORG_EMAIL=<ORG-EMAIL>
ORG_NAME=<ORG-NAME>
FONT=<FONT-FILE-NAME>
MJ_APIKEY_PUBLIC=<YOUR-MAILJET-PUBLIC-KEY>
MJ_APIKEY_PRIVATE=<YOUR-MAILJET-PRIVATE-KEY>
SG_APIKEY=<YOUR-SENDGRID-API-KEY>
```

Now simply run:
Expand Down
Binary file modified __pycache__/html.cpython-37.pyc
Binary file not shown.
25 changes: 4 additions & 21 deletions idgen_mailjet.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from html import html
from mail_temp import mail_temp

from dotenv import load_dotenv
load_dotenv()
Expand All @@ -32,8 +32,8 @@
SCOPES = ['https://www.googleapis.com/auth/spreadsheets.readonly']

# ID of spreadsheet : https://docs.google.com/spreadsheets/d/<THIS-PART-IS-ID>/edit#gid=0
SAMPLE_SPREADSHEET_ID = os.getenv('SHEET_ID')
SAMPLE_RANGE_NAME = 'A139:V339'
SAMPLE_SPREADSHEET_ID = os.getenv('SHEET_ID_TEST')
SAMPLE_RANGE_NAME = 'A2:V2'


def main():
Expand Down Expand Up @@ -133,23 +133,6 @@ def main():
draw.text(((321 - x / 2), (810 - y / 2)),
inst, font=font, fill='black')

# Get and paste the profile picture
# print('\tGetting profile picture...')
# imageResponse = requests.get(imageUrl)
# profileImage = Image.open(BytesIO(imageResponse.content))

# profileImage.thumbnail((288, 288), Image.ANTIALIAS)

# # Make the image a circle
# bigsize = (profileImage.size[0] * 3, profileImage.size[1] * 3)
# mask = Image.new('L', bigsize, 0)
# maskDraw = ImageDraw.Draw(mask)
# maskDraw.ellipse((0,0) + bigsize, fill=255)
# mask = mask.resize(profileImage.size, Image.ANTIALIAS)
# profileImage.putalpha(mask)

# template.paste(profileImage, (175, 282), profileImage)

# Add abstract element
element = Image.open('element.png')
element.thumbnail((59, 59), Image.ANTIALIAS)
Expand All @@ -176,7 +159,7 @@ def main():
}
],
"Subject": "[ID Card] GDG Gandhinagar - DevFest 2019",
"HTMLPart": html(name, email),
"HTMLPart": mail_temp(name, email),
"Attachments": [
{
"Filename": name + '.png',
Expand Down
173 changes: 173 additions & 0 deletions idgen_sendgrid.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,173 @@
from __future__ import print_function
import json
import os
import base64
from io import BytesIO
import requests
import math
from PIL import Image, ImageDraw, ImageFont
import qrcode.image.svg
import qrcode
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from mail_temp import mail_temp
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail, Attachment, Content

from dotenv import load_dotenv
load_dotenv()


API_KEY = os.getenv('SG_APIKEY')
ORG_EMAIL = os.getenv('ORG_EMAIL')
ORG_NAME = os.getenv('ORG_NAME')
FONT = os.getenv('FONT')

sg = SendGridAPIClient(API_KEY)

# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/spreadsheets.readonly']

# ID of spreadsheet : https://docs.google.com/spreadsheets/d/<THIS-PART-IS-ID>/edit#gid=0
SAMPLE_SPREADSHEET_ID = os.getenv('SHEET_ID_TEST')
SAMPLE_RANGE_NAME = 'A2:V2'


def main():
print("Getting data from the sheet...")

creds = None

if os.path.exists('token.pickle'):
with open('token.pickle', 'rb') as token:
creds = pickle.load(token)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
'credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open('token.pickle', 'wb') as token:
pickle.dump(creds, token)

service = build('sheets', 'v4', credentials=creds)

# Call the Sheets API
sheet = service.spreadsheets()
result = sheet.values().get(spreadsheetId=SAMPLE_SPREADSHEET_ID,
range=SAMPLE_RANGE_NAME).execute()
values = result.get('values', [])

if not values:
print('No data found.')
else:
# We can access the sheet values here
print("Data received.")

for row in values:
reg_id = row[0]
name = row[1] + ' ' + row[2]
email = row[3]
designation = row[18]
inst = row[19]
org = row[21]

print('Generating card for %s...' % (name))

qr = qrcode.QRCode(
version=1,
error_correction=qrcode.constants.ERROR_CORRECT_M,
box_size=10,
border=2,
)
qr.add_data(reg_id)
qr.make(fit=True)
img = qr.make_image()

# Resize the QR code to 150px X 150px
img.thumbnail((221, 221), Image.ANTIALIAS)

img.save(os.path.join('qrcodes', email + '.png'))

template = Image.open('template.png')

# Paste QR code
template.paste(img, (205, 360))

# Write the name
draw = ImageDraw.Draw(template)
font = ImageFont.truetype(FONT, 55)

x, y = font.getsize(name)

draw.text(((321 - x / 2), (710 - y / 2)),
name, font=font, fill='black')

# Write the designation
if designation != 'NA':
draw = ImageDraw.Draw(template)
font = ImageFont.truetype(FONT, 26)
x, y = font.getsize(designation)
draw.text(((321 - x / 2), (770 - y / 2)),
designation, font=font, fill='black')

if org != 'NA':
draw = ImageDraw.Draw(template)
font = ImageFont.truetype(FONT, 30)
x, y = font.getsize(org)

draw.text(((321 - x / 2), (810 - y / 2)),
org, font=font, fill='black')

elif inst != 'NA':
draw = ImageDraw.Draw(template)
font = ImageFont.truetype(FONT, 30)
x, y = font.getsize(inst)

draw.text(((321 - x / 2), (810 - y / 2)),
inst, font=font, fill='black')

# Add abstract element
element = Image.open('element.png')
element.thumbnail((59, 59), Image.ANTIALIAS)
template.paste(element, (407, 557), element)
# Save the card
template.save(os.path.join('cards', email + '.png'))

buffer = BytesIO()
template.save(buffer, format="PNG")
base64Value = base64.b64encode(buffer.getvalue())

message = Mail(
from_email=(ORG_EMAIL, "GDG Gandhinagar"),
subject="[ID Card] GDG Gandhinagar - DevFest 2019",
to_emails=[(email, name)],
html_content=Content("text/html", mail_temp(name, email)))

attachment = Attachment()
attachment.file_content = base64Value.decode()
attachment.file_type = "image/png"
attachment.file_name = "{}.png".format(name)
attachment.disposition = "attachment"

message.add_attachment(attachment)

print("\tSending mail to " + name + "...")

result = sg.client.mail.send.post(message.get())
if result.status_code == 200:
print("\t\tMail sent.")
else:
print("\t\tMail not sent.")

print('All cards sent successfully.')


if __name__ == '__main__':
main()
2 changes: 1 addition & 1 deletion html.py → mail_temp.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from string import Template


def html(name, email):
def mail_temp(name, email):
tweet = "I'm glad to tell that I will be attending DevFest Gandhinagar on 13th October. @GDG_Gandhinagar"
hashtags = "DevFestGnr,DevFest19,GDGGnr,WTMGnr,DevFest"
htmlString = Template('''
Expand Down

0 comments on commit df61cb3

Please sign in to comment.