我一直在用python编写程序来自动发送电子邮件。应该很简单。
我尝试了多种不同的方法,并且在尝试了一个新的非常规模块一个小时之后,我终于了解了我现在拥有的代码。
import smtplib, ssl
port = 587
server_name = 'smtp.gmail.com'
email = 'not_telling_you@my_email.com'
recipient = 'not_telling_you1@my_email.com'
message = 'Hello world'
context = ssl.create_default_context()
print('Having trouble? Go to "accounts.google.com > settings > less secure app access > turn on access > on" when using a gmail account. It is not recommended to do this with your normal account.')
import tkinter as tk
class Application(tk.Frame):
def __init__(self, master=None):
super().__init__(master)
self.master = master
self.pack()
self.create_widgets()
def create_widgets(self):
self.hi_there = tk.Button(self)
self.hi_there["text"] = "Log in"
self.hi_there["command"] = self.login
self.hi_there.pack(side="top")
self.quit = tk.Button(self, text="QUIT", fg="red",
command=self.master.destroy)
self.quit.pack(side="bottom")
def login(self):
server = smtplib.SMTP(server_name, port)
print('Connecting to server...')
server.ehlo()
server.starttls()
server.ehlo()
print('Successfully connected to', server_name, 'through port', port)
print('Logging in...')
server.login(email,'****************')
print('Successfully logged into', email)
server.sendmail(email, recipient, message)
print('Successfully sent', message, 'from', email, 'to', recipient)
root = tk.Tk()
app = Application(master=root)
app.mainloop()
它应该简单地在用户单击登录时自动发送电子邮件(我没有费心去更改它的显示内容,我是在一些旧程序的基础上构建的)。它到达发件人电子邮件的已发件箱,但收件人永远不会收到该电子邮件。