Pythonでのメール送信

Pythonを使ったメール送信の基礎をご紹介します。

SMTPを利用した安全な送信方法を学びましょう。

サンプルコード

        
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

smtp_server = 'mail78.conoha.ne.jp'
smtp_port = 465
username = 'info@hackun.net'
password = 'your_password'
from_email = 'info@hackun.net'
to_email = 'example@example.com'

msg = MIMEMultipart()
msg['From'] = from_email
msg['To'] = to_email
msg['Subject'] = 'テストメール'
msg.attach(MIMEText('これはテストメールです。', 'plain'))

try:
    server = smtplib.SMTP_SSL(smtp_server, smtp_port)
    server.login(username, password)
    server.sendmail(from_email, to_email, msg.as_string())
    print("メール送信成功!")
except Exception as e:
    print(f"エラー: {e}")
finally:
    server.quit()
        
        
    

コードの詳細な解説をします。

SMTP_SSLを用いることで、安全な接続が可能です。