Pythonを使用してGmailをプロバイダーとしてメールを送信する方法

PYTHON3 チュートリアル

PythonでGmailを使用してメールを送信する方法

Pythonを使用してGmailを介してメールを送信することは、多くのアプリケーションで役立つスキルです。特に、自動化された通知やレポートの送信に便利です。本記事では、Pythonを使ってGmailをプロバイダーとしてメールを送信する方法を詳しく解説します。必要なライブラリや設定、具体的なコード例を紹介します。

必要なライブラリと設定

まず、PythonでGmailを使用してメールを送信するためには、smtplibライブラリを使用します。このライブラリは標準ライブラリに含まれているため、追加のインストールは必要ありません。ただし、Gmailアカウントで「安全性の低いアプリのアクセス」を許可する必要があります。

Gmailの設定

Gmailを使用する前に、Gmailの設定で「安全性の低いアプリのアクセス」を有効にする必要があります。これは、Gmailのセキュリティ設定で行います。Googleアカウントにログインし、[セキュリティ]タブから設定を変更してください。ただし、2022年5月30日以降、この設定はGoogleによって段階的に廃止されています。そのため、アプリパスワードを使用することをお勧めします。

基本的なメール送信のコード例

以下に、Pythonを使用してGmailを介してメールを送信する基本的なコード例を示します。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
import smtplib
from email.mime.text import MIMEText
def send_email(subject, body, to_email):
from_email = "your-email@gmail.com"
password = "your-email-password"
# メールの内容を設定
msg = MIMEText(body)
msg['Subject'] = subject
msg['From'] = from_email
msg['To'] = to_email
# GmailのSMTPサーバーに接続
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(from_email, password)
# メールを送信
server.sendmail(from_email, to_email, msg.as_string())
server.quit()
# 使用例
send_email("テストメール", "これはPythonから送信されたテストメールです。", "recipient-email@example.com")
import smtplib from email.mime.text import MIMEText def send_email(subject, body, to_email): from_email = "your-email@gmail.com" password = "your-email-password" # メールの内容を設定 msg = MIMEText(body) msg['Subject'] = subject msg['From'] = from_email msg['To'] = to_email # GmailのSMTPサーバーに接続 server = smtplib.SMTP('smtp.gmail.com', 587) server.starttls() server.login(from_email, password) # メールを送信 server.sendmail(from_email, to_email, msg.as_string()) server.quit() # 使用例 send_email("テストメール", "これはPythonから送信されたテストメールです。", "recipient-email@example.com")
import smtplib
from email.mime.text import MIMEText

def send_email(subject, body, to_email):
    from_email = "your-email@gmail.com"
    password = "your-email-password"

    # メールの内容を設定
    msg = MIMEText(body)
    msg['Subject'] = subject
    msg['From'] = from_email
    msg['To'] = to_email

    # GmailのSMTPサーバーに接続
    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.starttls()
    server.login(from_email, password)

    # メールを送信
    server.sendmail(from_email, to_email, msg.as_string())
    server.quit()

# 使用例
send_email("テストメール", "これはPythonから送信されたテストメールです。", "recipient-email@example.com")

このコードでは、smtplibを使用してGmailのSMTPサーバーに接続し、メールを送信しています。MIMETextを使用してメールの内容を設定します。

HTMLメールを送信する方法

HTML形式のメールを送信することも可能です。以下にそのコード例を示します。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
def send_html_email(subject, html_body, to_email):
from_email = "your-email@gmail.com"
password = "your-email-password"
# メールの内容を設定
msg = MIMEMultipart()
msg['Subject'] = subject
msg['From'] = from_email
msg['To'] = to_email
# HTMLとしてメールの本文を設定
msg.attach(MIMEText(html_body, 'html'))
# GmailのSMTPサーバーに接続
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(from_email, password)
# メールを送信
server.sendmail(from_email, to_email, msg.as_string())
server.quit()
# 使用例
html_content = "<h1>HTMLメール</h1><p>これは<b>HTML</b>形式のメールです。</p>"
send_html_email("HTMLテストメール", html_content, "recipient-email@example.com")
from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText def send_html_email(subject, html_body, to_email): from_email = "your-email@gmail.com" password = "your-email-password" # メールの内容を設定 msg = MIMEMultipart() msg['Subject'] = subject msg['From'] = from_email msg['To'] = to_email # HTMLとしてメールの本文を設定 msg.attach(MIMEText(html_body, 'html')) # GmailのSMTPサーバーに接続 server = smtplib.SMTP('smtp.gmail.com', 587) server.starttls() server.login(from_email, password) # メールを送信 server.sendmail(from_email, to_email, msg.as_string()) server.quit() # 使用例 html_content = "<h1>HTMLメール</h1><p>これは<b>HTML</b>形式のメールです。</p>" send_html_email("HTMLテストメール", html_content, "recipient-email@example.com")
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

def send_html_email(subject, html_body, to_email):
    from_email = "your-email@gmail.com"
    password = "your-email-password"

    # メールの内容を設定
    msg = MIMEMultipart()
    msg['Subject'] = subject
    msg['From'] = from_email
    msg['To'] = to_email

    # HTMLとしてメールの本文を設定
    msg.attach(MIMEText(html_body, 'html'))

    # GmailのSMTPサーバーに接続
    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.starttls()
    server.login(from_email, password)

    # メールを送信
    server.sendmail(from_email, to_email, msg.as_string())
    server.quit()

# 使用例
html_content = "

HTMLメール

これはHTML形式のメールです。

" send_html_email("HTMLテストメール", html_content, "recipient-email@example.com")

この例では、MIMEMultipartを使用して、HTML形式のメールを送信しています。HTMLコンテンツをMIMETextに渡す際に、'html'を指定します。

添付ファイル付きメールの送信

メールにファイルを添付することも可能です。以下にそのコード例を示します。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
from email.mime.application import MIMEApplication
def send_email_with_attachment(subject, body, to_email, file_path):
from_email = "your-email@gmail.com"
password = "your-email-password"
# メールの内容を設定
msg = MIMEMultipart()
msg['Subject'] = subject
msg['From'] = from_email
msg['To'] = to_email
# テキストとしてメールの本文を設定
msg.attach(MIMEText(body, 'plain'))
# ファイルを添付
with open(file_path, "rb") as file:
part = MIMEApplication(file.read(), Name=file_path)
part['Content-Disposition'] = f'attachment; filename="{file_path}"'
msg.attach(part)
# GmailのSMTPサーバーに接続
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(from_email, password)
# メールを送信
server.sendmail(from_email, to_email, msg.as_string())
server.quit()
# 使用例
send_email_with_attachment("添付ファイル付きメール", "ファイルを添付しています。", "recipient-email@example.com", "path/to/file.txt")
from email.mime.application import MIMEApplication def send_email_with_attachment(subject, body, to_email, file_path): from_email = "your-email@gmail.com" password = "your-email-password" # メールの内容を設定 msg = MIMEMultipart() msg['Subject'] = subject msg['From'] = from_email msg['To'] = to_email # テキストとしてメールの本文を設定 msg.attach(MIMEText(body, 'plain')) # ファイルを添付 with open(file_path, "rb") as file: part = MIMEApplication(file.read(), Name=file_path) part['Content-Disposition'] = f'attachment; filename="{file_path}"' msg.attach(part) # GmailのSMTPサーバーに接続 server = smtplib.SMTP('smtp.gmail.com', 587) server.starttls() server.login(from_email, password) # メールを送信 server.sendmail(from_email, to_email, msg.as_string()) server.quit() # 使用例 send_email_with_attachment("添付ファイル付きメール", "ファイルを添付しています。", "recipient-email@example.com", "path/to/file.txt")
from email.mime.application import MIMEApplication

def send_email_with_attachment(subject, body, to_email, file_path):
    from_email = "your-email@gmail.com"
    password = "your-email-password"

    # メールの内容を設定
    msg = MIMEMultipart()
    msg['Subject'] = subject
    msg['From'] = from_email
    msg['To'] = to_email

    # テキストとしてメールの本文を設定
    msg.attach(MIMEText(body, 'plain'))

    # ファイルを添付
    with open(file_path, "rb") as file:
        part = MIMEApplication(file.read(), Name=file_path)
        part['Content-Disposition'] = f'attachment; filename="{file_path}"'
        msg.attach(part)

    # GmailのSMTPサーバーに接続
    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.starttls()
    server.login(from_email, password)

    # メールを送信
    server.sendmail(from_email, to_email, msg.as_string())
    server.quit()

# 使用例
send_email_with_attachment("添付ファイル付きメール", "ファイルを添付しています。", "recipient-email@example.com", "path/to/file.txt")

このコードでは、MIMEApplicationを使用してファイルを添付しています。Content-Dispositionヘッダーを設定することで、ファイル名を指定します。

まとめ

Pythonを使用してGmailを介してメールを送信する方法を学びました。smtplibemailモジュールを組み合わせることで、テキストメール、HTMLメール、添付ファイル付きメールを簡単に送信できます。セキュリティの観点から、Googleアカウントの設定を適切に行い、アプリパスワードを使用することをお勧めします。

Pythonを使用してGmailをプロバイダーとしてメールを送信する方法について説明します。

1. Gmail APIを有効化する: まず、Google Cloud Platformで新しいプロジェクトを作成し、Gmail APIを有効化します。APIキーと認証情報を取得しておきます。

2. PythonのSMTPライブラリを使用する: Pythonのsmtplibモジュールを使用して、GmailのSMTPサーバーを介してメールを送信します。以下は簡単な例です。

“`python
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

# GmailのSMTPサーバーに接続
server = smtplib.SMTP(‘smtp.gmail.com’, 587)
server.starttls()

# Gmailアカウントにログイン
server.login(“your_email@gmail.com”, “your_password”)

# メールの作成
msg = MIMEMultipart()
msg[‘From’] = “your_email@gmail.com”
msg[‘To’] = “recipient_email@example.com”
msg[‘Subject’] = “Subject of the email”
body = “Body of the email”
msg.attach(MIMEText(body, ‘plain’))

# メールを送信
server.send_message(msg)

# SMTPサーバーから切断
server.quit()
“`

3. セキュリティ設定の確認: Gmailのセキュリティ設定で「安全性の低いアプリのアクセス」を有効にしておく必要があります。

以上がPythonを使用してGmailをプロバイダーとしてメールを送信する方法の基本的な手順です。詳細や応用例については、公式ドキュメントやサンプルコードを参照してください。

購読
通知


0 Comments
Inline Feedbacks
View all comments