使用Google App Engine发送附件

时间:2013-06-20 16:23:59

标签: python google-app-engine email

我有一个简单的webapp,用户可以提交附件以及提交的信息。我认为我已正确上传附件,但我不确定如何将其附加到服务器(GAE)端生成的电子邮件中。这是我的html表单

<form action="http://xxx.appspot.com" enctype="multipart/form-data;charset=UTF-8" target="myiframe" method="post" id="myForm" name="myForm">Contact Name<br />
<input type="text" required="" name="cname" /><br />
Name of Institution<br />
<input type="text" required="" name="iname" /><br />
E-Mail<br />
<input type="email" required="" name="email" /><br />
Phone<br />
<input type="tel" required="" name="phone" /><br />
If you have a supporting file that will clarify your help request you can add it here (optional)<br />
<input type="file" name="upfile" MAXLENGTH=50 ALLOW="text/html/text/plain" /><br />
Description of problem/issue<br />
<textarea required="" name="desc" rows="3" cols="30">
</textarea>
<br />
<input type="submit" value="Submit" />
<div id="result"></div>
</form>
<iframe name="myiframe" style="visibility:hidden;display:none" src="http://xxx.appspot.com" id="myiframe"></iframe>

这是我的服务器端代码

import cgi, cgitb
from google.appengine.api import mail

class MainPage(webapp2.RequestHandler):

    def get(self):
        self.response.headers['Content-Type'] = 'text/plain'
        self.response.write('Hello, webapp2 World!')

    def post(self):

        contact=self.request.POST["cname"]
        institute=self.request.POST["iname"]
        email=self.request.POST["email"]
        phone=self.request.POST["phone"]
        desc=self.request.POST["desc"]
        filename=self.request.POST["upfile"]
        user_address = "xxx@xxx.net"

        sender_address = "xxx@gmail.com"
        subject = "Test email"

        body = "Contact Name: "+contact+"\n"+"Name of Institution: "+institute+"\n"+"E-mail: "+email+"\n"+"Phone: "+phone+"\n"+"Description: "+desc#+"\n"+"Filename: "+filename
        mail.send_mail(sender_address, user_address, subject, body)

application = webapp2.WSGIApplication([('/', MainPage)], debug=True)

使用GAE文档的问题在于,我认为,我没有按照它们的方式上传文件。我在这里完全不知所措。

编辑:我已添加

mail.send_mail(sender_address, user_address, subject, body, attachments=[(filename), (filename)])

但只附加文字文件名,而不是内容。

1 个答案:

答案 0 :(得分:0)

attachments元组中的第二项需要是文件内容:

 ... attachments=[(filename), (file_contents)]

请参阅documentation