0
0

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 1 year has passed since last update.

SMTPLIBを使ったGmailの送信サンプルコード

Last updated at Posted at 2022-02-13

SMTPLIBを使ったGmailの送信サンプルコードです。

gmail.JPG

#####ライブラリのインポート

import smtplib, ssl
from email.mime.text import MIMEText
import schedule
import time
import openpyxl as px #Excelのメーリングリスト取得用

#####Gmailの設定・ファイルの読込

# Gmailの設定
mail_from = "genbaneko@gmail.com"
app_password = "genba1234"

# メールの送信先
filepath = 'customerlist.xlsx'
wb = px.load_workbook(filename=filepath)
ws1 = wb['メールリスト']
to_users = sh1_values=[[cell1.value for cell1 in row1] for row1 in ws1]

# 添付ファイル
with open(r"C:\genbaneko.jpg", "rb") as atch_f:
attachment = MIMEApplication(atch_f.read())

# 文字コード設定
charset = 'utf-8'

#####メール送信

def mail_send():
	# Gmailに接続
	server = smtplib.SMTP_SSL("smtp.gmail.com", 465,
	context=ssl.create_default_context())
	server.login(mail_from, app_password)

	for user in to_users: #for文で複数人に送信

	subject = f"""ヒヤリハット報告"""
	body = f""" ~ここにメール本文を記載~ """
	msg = MIMEText(body, "plain", charset)

	msg["Subject"] = subject
	msg["To"] = user['address']
	msg["From"] = mail_from

	msg.attach(attachment) #添付ファイル
	server.send_message(msg) # メールの送信

schedule.every(7).days.do(mail_send) #7日に1回送信
while True:
	schedule.run_pending()
	time.sleep(1)

##参考
YouTubeで「Pythonを使った事務処理の効率化」というタイトルで、メール送信について紹介。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?