如何用代码发送电子邮件?

2025-10发布6次浏览

发送电子邮件可以通过多种编程语言实现,其中最常用的两种语言是Python和JavaScript。下面我将分别介绍如何使用这两种语言发送电子邮件。

Python 发送电子邮件

Python 使用 smtplibemail 模块来发送电子邮件。下面是一个简单的例子:

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

# 设置发件人和收件人邮箱
sender_email = "your-email@example.com"
receiver_email = "receiver-email@example.com"

# 创建邮件对象
message = MIMEMultipart()
message["From"] = sender_email
message["To"] = receiver_email
message["Subject"] = "Subject of the Email"

# 添加邮件正文
body = "This is the body of the email"
message.attach(MIMEText(body, "plain"))

# SMTP服务器设置
smtp_server = "smtp.example.com"
smtp_port = 587
smtp_user = "your-email@example.com"
smtp_password = "your-password"

# 连接SMTP服务器并发送邮件
try:
    server = smtplib.SMTP(smtp_server, smtp_port)
    server.starttls()
    server.login(smtp_user, smtp_password)
    text = message.as_string()
    server.sendmail(sender_email, receiver_email, text)
    print("Email sent successfully")
except Exception as e:
    print(f"Error: {e}")
finally:
    server.quit()

JavaScript 发送电子邮件

JavaScript 通常不直接用于发送电子邮件,因为出于安全和隐私的原因,大多数浏览器都不允许网页直接发送电子邮件。但是,你可以使用Node.js和Nodemailer库来在服务器端发送电子邮件。

首先,你需要安装Nodemailer:

npm install nodemailer

然后,你可以使用以下代码来发送电子邮件:

const nodemailer = require('nodemailer');

// 创建一个 transporter 对象用于发送邮件
let transporter = nodemailer.createTransport({
    service: 'gmail',
    auth: {
        user: 'your-email@gmail.com',
        pass: 'your-password'
    }
});

// 设置邮件选项
let mailOptions = {
    from: 'your-email@gmail.com',
    to: 'receiver-email@example.com',
    subject: 'Subject of the Email',
    text: 'This is the body of the email'
};

// 发送邮件
transporter.sendMail(mailOptions, function(error, info){
    if (error) {
        console.log(error);
    } else {
        console.log('Email sent: ' + info.response);
    }
});

请注意,使用这些代码示例发送电子邮件时,确保你理解并遵守相关的电子邮件发送政策和法规,如SPAM法案。