我遇到这问题的时候的源代码:
try:
smtp=smtplib.SMTP()
smtp.connect('smtp.163.com',25)
smtp.login('...','...')
smtp.sendmail('[email protected]','[email protected]',MIMEText('老八秘制小汉堡').as_string())
smtp.close()
except Exception as e:
print(e)
然后
(220, b'163.com Anti-spam GT for Coremail System (163com[20141201])')
(500, b'Error: bad syntax')
我觉得十分莫名其妙,网上有人说是因为socket.getfqdn()不是主机地址,然后搬出来一堆我看不懂得代码,,,(self没有在类里面用,一堆没啥用的变量)
我就去掉try了,一行一行的试,然后打错了,返回了一关键错误代码
>>> smtp.sendmail('[email protected]',['[email protected]'],MIMEText('wdwd').as_string())
Traceback (most recent call last):
File "" , line 1, in <module>
smtp.sendmail('[email protected]',['[email protected]'],MIMEText('wdwd').as_string())
File "A:\Python\lib\smtplib.py", line 871, in sendmail
raise SMTPSenderRefused(code, resp, from_addr)
smtplib.SMTPSenderRefused: (503, b'Error: send HELO/EHLO first', '[email protected]')
我一看,原来SMTP类还有个ehlo函数(要写在login函数之前)不过不能直接用,参数要写邮箱的smtp地址:
>>> smtp.ehlo('smtp.163.com')
(250, b'mail\nPIPELINING\nAUTH LOGIN PLAIN\nAUTH=LOGIN PLAIN\ncoremail ............................................\nSTARTTLS\n..........') #原来的东西被我用点替换了,反正我觉得暴露出去挺危险的
然后看这架势就大功告成了,最后在登入
>>> smtp.login('.......','..........')
(235, b'Authentication successful')
这下就可以愉快的sendmail了
>>> smtp.sendmail('[email protected]',['[email protected]'],MIMEText('wdwd').as_string())
{
}
源代码:
import smtplib
from email.mime.text import MIMEText
from email.header import Header
class Mail:
'''('sender':(String) Mail sender,
'sendto':(Tuple or List) Mail receivers,
'smtp_host':(String) SMTP Server host,
'smtp_port':(Int) SMTP Server port,
'smtp_user':(String) SMTP Server user,
'smtp_userpwd':(String) SMTP Server user's password,
'subject':(String) The title of mail,
'content':(String) The content of mail,
'sendspr':(String) The type of content(such as html,plain...)'''
def __init__(self,**args):
self.sender = ''
self.sendto = []
self.smtp_host = ''
self.smtp_port = 0
self.smtp_user = ''
self.smtp_userpwd = ''
self.subject = ''
self.content = ''
self.sendspr = 'plain' #'plain','html'
for i in args:
if i in self.__dict__:
self.__dict__[i] = args[i]
def send(self):
try:
self.smtp = smtplib.SMTP(self.smtp_host,self.smtp_port)
self.smtp.ehlo(self.smtp_host)
self.smtp.login(self.smtp_user,self.smtp_userpwd)
mime = MIMEText(self.content,self.sendspr,'utf-8')
mime['From'] = Header(self.sender,'utf-8')
mime['To'] = Header(';'.join(self.sendto),'utf-8')
mime['Subject'] = Header(self.subject,'utf-8')
self.smtp.sendmail(self.smtp_user,self.sendto,mime.as_string())
self.smtp.close()
except Exception as e:
print(e)