Python 如何在不登录服务器的情况下发送电子邮件

How to send an email without login to server in Python

我想在不登录 Python 的服务器的情况下发送电子邮件。我正在使用 Python 3.6。 我尝试了一些代码但收到错误。这是我的代码:

import smtplib                          

smtpServer='smtp.yourdomain.com'      
fromAddr='from@Address.com'         
toAddr='to@Address.com'     
text= "This is a test of sending email from within Python."
server = smtplib.SMTP(smtpServer)
server.set_debuglevel(1)         
server.sendmail(fromAddr, toAddr, text) 
server.quit()

我希望在不询问用户 ID 和密码的情况下发送邮件,但出现错误:

"smtplib.SMTPSenderRefused: (530, b'5.7.1 Client was not authenticated', 'from@Address.com')"

下面的代码对我有用。 首先,我通过Network Team opened/enabled端口25并在程序中使用它。

import smtplib                          
smtpServer='smtp.yourdomain.com'      
fromAddr='from@Address.com'         
toAddr='to@Address.com'     
text= "This is a test of sending email from within Python."
server = smtplib.SMTP(smtpServer,25)
server.ehlo()
server.starttls()
server.sendmail(fromAddr, toAddr, text) 
server.quit()

我是这样用的。它在我的私人 SMTP 服务器上对我有用。

import smtplib

host = "server.smtp.com"
server = smtplib.SMTP(host)
FROM = "testpython@test.com"
TO = "bla@test.com"
MSG = "Subject: Test email python\n\nBody of your message!"
server.sendmail(FROM, TO, MSG)

server.quit()
print ("Email Send")
import win32com.client as win32
outlook=win32.Dispatch('outlook.application')
mail=outlook.CreateItem(0)
mail.To='To address'
mail.Subject='Message subject'
mail.Body='Message body'
mail.HTMLBody='<h2>HTML Message body</h2>' #this field is optional

# To attach a file to the email (optional):
attachment="Path to the attachment"
mail.Attachments.Add(attachment)

mail.Send()

首先,您必须有一个 SMTP 服务器才能发送电子邮件。如果没有,通常会使用 outlook 的服务器。但是outlook只接受认证用户,所以如果不想登录服务器,就得选择不需要认证的服务器。

第二种方法是设置内部 SMTP 服务器。设置内部 SMTP 服务器后,您可以使用“localhost”作为发送电子邮件的服务器。像这样:

import smtplib
receiver = 'someonesEmail@hisDomain.com'
sender = 'yourEmail@yourDomain.com'
smtp = smtplib.SMTP('localhost')

subject = 'test'
body = 'testing plain text message'
msg = 'subject: ' + subject + ' \n\n' + body

smtp.sendmail('sender', receiver, msg)