在Mailgun教程之后,我可以通过Mailgun在Python中发送包含请求库的电子邮件。
我需要使用" httplib" (不是请求!)在Python中发送电子邮件。但是,Mailgun教程没有提供如何使用httplib的任何示例。
# this is a "requests" example from the Mailgun tutorial
requests.post(
"https://api.mailgun.net/v3/" + env.MG_SANDBOX_DOMAIN_NAME + "/messages",
auth=("api", env.MG_KEY),
files=[("attachment", open(my_PDF_full_path))],
data={
"from": "myemail@domain.com",
"to": "youremail@domain.com",
"subject": "TESTING EMAIL",
"text": "TESTING EMAIL",
"html": "<p>TESTING EMAIL</p"
}
)
如何将此示例转换为使用&#34; httplib&#34;的代码? Python中的库?
答案 0 :(得分:1)
以下适用于我。
import httplib
import base64
import urllib
params = urllib.urlencode({
'from': 'from@someone.com',
'to': 'to@someone.com',
'subject': 'This is a test',
'text': 'Hello\nThis is a test message.'
})
headers = {
'Authorization': 'Basic {0}'.format(base64.b64encode("api:key-myapikey")),
'Content-Type': 'application/x-www-form-urlencoded'
}
conn = httplib.HTTPSConnection("api.mailgun.net", 443)
conn.request('POST', '/v3/my-sandbox.mailgun.org/messages', params, headers)
response = conn.getresponse()
print response.status, response.reason
data = response.read()
print data
conn.close()
如果您需要发送附件,则需要更多工作。
答案 1 :(得分:0)
我使用此函数发送带有Python3的电子邮件,不需要外部库。
import urllib.request
import urllib.parse
def send_mg_mail(account='', key='', addr_to='', m_subject='', m_text=''):
mg_url = 'https://api.mailgun.net/v3/{0}.mailgun.org/messages'.format(account)
addr_from = "user <user@{0}.mailgun.org>".format(account)
data = urllib.parse.urlencode({"from": addr_from, "to": addr_to, "subject": m_subject, "text":m_text})
data = data.encode('ascii')
auth_handler = urllib.request.HTTPBasicAuthHandler()
auth_handler.add_password(user="api", realm='MG API', passwd=key, uri=mg_url)
opener = urllib.request.build_opener(auth_handler)
urllib.request.install_opener(opener)
d = urllib.request.urlopen(mg_url, data)
ret_code = str(d.code) + " " + d.reason
print(ret_code)
键的格式为:
key-<numbers>
检查您的mailgun帐户以获取&#34;帐户&#34;字符串,可能是这样的:
sandbox123456789abcdefgh...
答案 2 :(得分:0)
我能够找到解决这个问题的方法,我使用了multipart_encode和MultipartParam lib
load = {
"from": messages['from'],
"to": messages['to'],
"subject": messages['subject'],
"text": messages['text'],
"attachment": MultipartParam(
"attachment",
filename=messages['filename'],
filetype='application/pdf',
value=messages['attachment'])
}
payload, hd = multipart_encode(load)
hd['Authorization'] = 'Basic %s' % (base64.b64encode(api),)
resp = urlfetch.fetch(url=url, payload="".join(payload), method='POST', headers=hd, validate_certificate=True)