要在Python中發(fā)送郵件,你可以使用內(nèi)置的smtplib庫(kù)。以下是一個(gè)簡(jiǎn)單的示例代碼,可以通過(guò)SMTP服務(wù)器發(fā)送電子郵件:
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):
# 創(chuàng)建郵件內(nèi)容
msg = MIMEText(message)
msg['Subject'] = subject
msg['From'] = from_email
msg['To'] = to_email
# 連接SMTP服務(wù)器并發(fā)送郵件
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)
在上面的示例中,你需要將示例數(shù)據(jù)替換為實(shí)際的SMTP服務(wù)器和電子郵件帳戶信息。此外,還需要安裝Python模塊email
和smtplib
,可以使用pip
命令進(jìn)行安裝。
請(qǐng)注意,有些SMTP服務(wù)器可能需要啟用SMTP身份驗(yàn)證或使用SSL / TLS加密。要進(jìn)行這些設(shè)置,請(qǐng)查閱你所使用的SMTP服務(wù)器的文檔。