首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >windows上的python 3.5。程序应该发送一个它读取的文本文件,然后发送一条emty消息。

windows上的python 3.5。程序应该发送一个它读取的文本文件,然后发送一条emty消息。
EN

Stack Overflow用户
提问于 2017-06-30 23:16:16
回答 2查看 53关注 0票数 0

我以前试过,但很管用,不知道会发生什么..首先,它应该读取一个文本文件。我试着手动阅读和打印它,它工作了,所以这部分是正常的。我认为。但每次我尝试发送消息时,都会收到一条空消息

代码语言:javascript
运行
复制
import smtplib as s

#file settings
filename = open("D:\pythonscripts\hey_hey.txt", 'a+')
content = filename.read()

#recivers list
recivers = ['somemail@gmail.com']

#tries to send the message
def send_mail(username, password, msg):

    #connects to smtp gmail server
    server = s.SMTP('smtp.gmail.com:587')
    server.starttls()
    server.login(username, password)
    try:
        server.sendmail(username, recivers[0], msg)
        print("massage sent")
    except:
        server.close()
        print("error while sending the massage\nquitung server...")


send_mail('somemail@gmail.com', 'ferari_car', content)
EN

回答 2

Stack Overflow用户

发布于 2017-06-30 23:20:08

试着这样做:

代码语言:javascript
运行
复制
filename = open("D:\\pythonscripts\\hey_hey.txt", 'r')  # r, not a+, and escape the backslashes

a+打开要追加的文件,这会将文件位置放在文件的末尾。所以当你试着读它的时候,你什么也得不到。

票数 2
EN

Stack Overflow用户

发布于 2017-07-01 19:30:33

嘿,大家好,谢谢你们帮我。很显然,我设法将邮件与文本文件一起作为附件发送,而不是邮件正文。

代码语言:javascript
运行
复制
import smtplib as s
from os.path import basename
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import COMMASPACE, formatdate

#file settings
filename = open("D:\\pythonscripts\\hey_hey.txt", 'r')
content= filename.read()
print(content)

#recivers list
recivers = ['somemail@gmail.com']

#tries to send the message
def send_mail(username, password, message, send_to, subject):
    #message settings
    msg = MIMEMultipart()
    msg['From'] = username
    msg['To'] = COMMASPACE.join(send_to)
    msg['Date'] = formatdate(localtime=True)
    msg['Subject'] = subject
    msg.attach(MIMEText(message))

    #connects to smtp gmail server
    server = s.SMTP('smtp.gmail.com:587')
    server.starttls()
    server.login(username, password)
    try:
        server.sendmail(username, send_to, msg.as_string())
        print("massage sent")
    except:
        server.close()
        print("error while sending the massage\nquitung server...")


send_mail('othermail@gmail.com', 'ferari_car', content, recivers[0], "the mail stuff")
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44849778

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档