curl或者python发送邮件


目录

[TOC]


curl

比如,Alice通过gmail([email protected])发送邮件给outlookBob([email protected])

Alice的邮箱密码是alice_gmail_password

curl --ssl-reqd smtps://$(dig +short MX gmail.com | sort -n | head -n1 | awk '{print $2}'):465 \
     --mail-from "[email protected]" \
     --mail-rcpt [email protected] \
     --upload-file <(printf "From: Alice <[email protected]>\nTo: Bob <[email protected]>\nSubject: Hello Bob! Here's Alice sending the email.\nDate: $(date -R)\n\nDear Bob,\nWhat a lovely day.\n") \
     --user '[email protected]:alice_gmail_password'

python版本

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

def send_email(smtp_server, smtp_port, sender_email, sender_password, recipient_email, subject, body):
    msg = MIMEMultipart()
    msg['From'] = sender_email
    msg['To'] = recipient_email
    msg['Subject'] = subject
    msg.attach(MIMEText(body, 'plain'))

    try:
        # 如果使用587端口,则使用STARTTLS
        if smtp_port == 587:
            with smtplib.SMTP(smtp_server, smtp_port) as server:
                server.starttls()  # 启用TLS
                server.login(sender_email, sender_password)
                server.sendmail(sender_email, recipient_email, msg.as_string())
        else:
            # 使用SSL连接
            with smtplib.SMTP_SSL(smtp_server, smtp_port) as server:
                server.login(sender_email, sender_password)
                server.sendmail(sender_email, recipient_email, msg.as_string())

        print("邮件发送成功!")
    except Exception as e:
        print(f"发送邮件时发生错误: {e}")

if __name__ == "__main__":
    smtp_server = "smtp.gmail.com"  # Gmail 的SMTP服务器地址
    smtp_port = 587  # Gmail 使用587端口
    sender_email = "[email protected]"  # 发件人邮箱地址
    sender_password = "alice_gmail_password"  # 发件人邮箱密码
    recipient_email = "[email protected]"  # 收件人邮箱地址
    subject = "Hello Bob! Here's Alice sending the email."  # 邮件主题
    body = "Dear Bob,\nWhat a lovely day."  # 邮件正文

    send_email(smtp_server, smtp_port, sender_email, sender_password, recipient_email, subject, body)

如果想在脚本中使用curl发送邮件可以参考这篇文章

Last modification:October 3, 2024
V50%看看实力