从Python程序发送邮件

1 投票
1 回答
746 浏览
提问于 2025-04-16 16:05

下面的代码中,系统发送的邮件都被放到了用户的垃圾邮件文件夹里。下面是相关的Python代码。我怀疑邮件的发件人显示的是root@。请问该如何修正这个问题呢?

  def sendmail(to,fr,subject,msg):
     sendmail_location = "/usr/sbin/sendmail" # sendmail location
     p = os.popen("%s -t" % sendmail_location, "w")
     p.write("From: %s\n" % fr)
     p.write("Reply-to: %s\n" % fr)
     p.write("To: %s\n" % to)
     p.write("Content-type: text/html\n")
     p.write("Subject: %s\n" % subject)
     p.write("\n") # blank line separating headers from body
     p.write(msg)
     status = p.close()

收到的邮件格式是

     Delivered-To: harry@8767@gmail.com
     Received: by 19.143.162.8 with SMTP id k6gm828f7tfe;
             Tue, 19 Apr 2011 22:42:17 -0700 (PDT)
     Received: by 10.68.9.168 with SMTP id a5try030f516pbb.481.1303278137028;
             Tue, 19 Apr 2011 22:42:17 -0700 (PDT)
     Return-Path: <root@.>
     Received: from  ([174.1.161.204])
             by mx.google.com with ESMTPS id v4si18etrt0pbr.108.2011.04.19.22.42.15
             (version=TLSv1/SSLv3 cipher=OTHER);
             Tue, 19 Apr 2011 22:42:15 -0700 (PDT)
     Received-SPF: neutral (google.com: 74.3.161.204 is neither permitted nor denied by best guess record for domain of root@.) client-ip=74.3.161.204;
     Authentication-Results: mx.google.com; spf=neutral (google.com: 174.1.161.204 is neither permitted nor denied by best guess record for domain of root@.) smtp.mail=root@.
     Received: (qmail 23122 invoked by uid 0); 19 Apr 2011 22:36:27 -0000
     Date: 19 Apr 2011 22:36:27 -0000
     Message-ID: <2010041954235627.25121.qmail@>
     From: admin@xxxxxx.com
     Subject: hi

1 个回答

3

你为什么直接使用sendmail这个程序呢?

其实,Python有一个很不错的smtplib模块,可以通过各种邮件服务器发送邮件,还有一个email模块,可以帮助你写出符合RFC-822标准的邮件。

你现在的做法可能不是最好的选择。

撰写回答