Pythonでメールを送信するコードの書き方
Pythonでメールを送信するには、組み込みのsmtplibライブラリを利用します。SMTPサーバを通じてメールを送信するための簡単なサンプルコードを示します。
import smtplib
from email.mime.text import MIMEText
def send_email(subject, message, from_email, to_email, smtp_server, smtp_port, smtp_username, smtp_password):
# 创建邮件内容
msg = MIMEText(message)
msg['Subject'] = subject
msg['From'] = from_email
msg['To'] = to_email
# 连接SMTP服务器并发送邮件
server = smtplib.SMTP(smtp_server, smtp_port)
server.login(smtp_username, smtp_password)
server.sendmail(from_email, [to_email], msg.as_string())
server.quit()
# 使用示例
subject = "Hello"
message = "This is a test email."
from_email = "from@example.com"
to_email = "to@example.com"
smtp_server = "smtp.example.com"
smtp_port = 587
smtp_username = "username"
smtp_password = "password"
send_email(subject, message, from_email, to_email, smtp_server, smtp_port, smtp_username, smtp_password)
上記の例では、実 SMTP サーバーとメールアカウント情報を、サンプルデータと置き換える必要があります。また、Python の email モジュールと smtplib モジュールをインストールする必要があり、 pip コマンドでインストールできます。
SMTPサーバによっては、SMTP認証の有効化や、SSL/TLS暗号化の使用が必要な場合があります。その設定方法については、お使いのSMTPサーバのドキュメントを参照してください。