3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Python】Gmail送信機能

Last updated at Posted at 2020-02-15
通知機能が欲しくて、gmailを飛ばす機能を作ったので記載します。 言語はpythonになります。

前提

gmailの初期設定では、pythonによるログインをセキュリティでブロックしています。 解除方法は、Gmailアカウントにある「安全性の低いアプリのアクセス」の設定を許可にすればOKです。 https://myaccount.google.com/security

送信メールの設定を行うクラスになります。
送信元、送信先、gmailのアカウントパスワードを初期化で設定し、
sendメソッドの引数の内容を設定します。

send_message.py
Learn more or give us feedback
from email.mime.text import MIMEText
from email.utils import formatdate
import smtplib

class Send_Message:
    fromaddress = 'sample@gmail.com'
    toaddress = 'sample@hotmail.co.jp'
    password = 'password'

    def __init__(self, fromaddress, toaddress, password):
        self.fromaddress = fromaddress
        self.toaddress = toaddress
        self.password = password


    def send(self, content):
        smtpobj = smtplib.SMTP('smtp.gmail.com', 587)
        smtpobj.ehlo()
        smtpobj.starttls()
        smtpobj.ehlo()
        smtpobj.login(self.fromaddress, self.password)

        msg = MIMEText(content)
        msg['Subject'] = 'subject'
        msg['From'] = self.fromaddress
        msg['To'] = self.toaddress
        msg['Date'] = formatdate()

        smtpobj.sendmail(self.fromaddress, self.toaddress, msg.as_string())
        smtpobj.close()

メインの処理になります。
ここで、送信元、送信先、パスワード、内容を設定し、
実行すればgmailにログインし、メールを送信します。

mail.py
from  send_message import Send_Message
import sys

def main():
    fromaddress = '@gmail.com'
    toaddress = '@gmail.com'
    password = ''
    content =""

    try:
        mail = Send_Message(fromaddress, toaddress, password)
        mail.send(content)
        print("success")
    except:
        print("error")

if __name__ == "__main__":
    main()

githubにソースをあげています。
https://github.com/kurihiro0119/gmail_send_API

3
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?