Skip to content

Instantly share code, notes, and snippets.

@shouhei
Last active March 25, 2016 09:24
Show Gist options
  • Save shouhei/bece053c1d239961afe4 to your computer and use it in GitHub Desktop.
Save shouhei/bece053c1d239961afe4 to your computer and use it in GitHub Desktop.
gmail send api | Gmailのapiでメールを送信するやーつ
#!/bin/zsh
CLIENT_ID=
CLIENT_SECRET=
CODE=
ACCESS_TOKEN=
REFRESH_TOKEN=
# @name get_token
# @params $1=client_id
# @params $2=client_secret
# @params $3=code
# @return json
function get_token(){
echo "curl -d client_id=$1 -d client_secret=$2 -d redirect_uri=urn:ietf:wg:oauth:2.0:oob -d grant_type=authorization_code -d code=$3 https://accounts.google.com/o/oauth2/token"
curl -d client_id=$1 -d client_secret=$2 -d redirect_uri=urn:ietf:wg:oauth:2.0:oob -d grant_type=authorization_code -d code=$3 https://accounts.google.com/o/oauth2/token
}
# @name reflesh
# @params $1=client_id
# @params $2=client_secret
# @params $3=reflesh_token
# @return json
function refresh(){
curl -d "client_id=$1&client_secret=$2&refresh_token=$3&grant_type=refresh_token" https://accounts.google.com/o/oauth2/token
}
# @name send_gmail
# @params $1 from_address
# @params $2 to_address
# @params $3 subject
# @params $4 body
# @return json
function send_gmail(){
local address=`echo $1 | base64`
local from="From: $1\r\n"
local to="To: $2\r\n"
local subject="Subject: $3\r\n"
local mime="MIME-Version: 1.0\r\n"
local content_type="Content-Type: text/plain; charset=\"UTF-8\"\r\n"
local content_transfer="Content-Transfer-Encoding: base64\r\n"
local send_date="Date: `date`\n"
local r="\r\n"
local body="$4\n"
# if you use osx
local json_data='{"raw":"'`echo $from$to$subject$mime$content_type$content_transfer$send_date$r$body | base64`'"}'
# if you use linux | tr -d '\n'
local json_data='{"raw":"'`echo $from$to$subject$mime$content_type$content_transfer$send_date$r$body | base64 | tr -d`'"}'
echo $json_data
curl \
-H "Authorization: Bearer $5"\
-H "Content-Type: application/json; charset=UTF-8"\
-X POST\
-d $json_data\
"https://www.googleapis.com/gmail/v1/users/[email protected]/messages/send"
}
#get_token $CLIENT_ID $CLIENT_SECRET $CODE
#refresh $CLIENT_ID $CLIENT_SECRET $REFRESH_TOKEN
#send_gmail @gmail.com" "@gmail.com" 'subject' 'body' $ACCESS_TOKEN
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment