使用Mailgun Python API发送HTML邮件失败,文本邮件可正常发送
Fixing HTML Email Delivery with Mailgun Python API
Got it, let's get your HTML emails sending smoothly! The issue with your current code is that it only specifies a plain text version of the email using the text parameter. To send HTML content, you just need to add an html field to your data payload. I also fixed a small bug with the attachment handling that could cause errors when no filename is provided.
Here's the modified function:
def send_email(mailtext, htmltext="", filename=""): # Only include attachment if filename is provided files = [("attachment", open(filename, "rb"))] if filename else [] requests.post( "https://api.mailgun.net/v3/mydomain.in/messages", auth=("api", "key-1234"), files=files, data={ "from": "Credit Card Manager <creditcards@mydomain.in>", "to": ["bob@mydomain.in"], "subject": "Summary of Credit Card payments due", "text": mailtext, # Plain text fallback for non-HTML clients "html": htmltext # Your HTML content goes here } )
How to Use It
Call the function with both plain text and HTML content to ensure compatibility across all email clients:
# Plain text version (for clients that don't support HTML) plain_text = "Hi Bob, here's your credit card payment summary... (plain text details)" # HTML version with formatting html_content = """ <html> <body> <h1 style="color: #2c3e50;">Credit Card Payment Summary</h1> <p>Hi Bob,</p> <p>Here’s your upcoming payment breakdown:</p> <table style="border-collapse: collapse; width: 100%;"> <tr> <th style="border: 1px solid #ddd; padding: 8px;">Card</th> <th style="border: 1px solid #ddd; padding: 8px;">Amount Due</th> <th style="border: 1px solid #ddd; padding: 8px;">Due Date</th> </tr> <tr> <td style="border: 1px solid #ddd; padding: 8px;">Card 1</td> <td style="border: 1px solid #ddd; padding: 8px;">$500.00</td> <td style="border: 1px solid #ddd; padding: 8px;">15th October</td> </tr> </table> <p>Thanks,<br>Credit Card Manager</p> </body> </html> """ # Send the email with both formats send_email(plain_text, html_content)
Key Tips:
- Including both
textandhtmlensures your email works for every recipient—HTML-capable clients show the formatted version, while others use the plain text fallback. - Double-check your HTML for well-formed tags (no unclosed elements) to avoid rendering glitches.
- Use
rb(read binary) mode when opening attachment files to handle all file types correctly.
内容的提问来源于stack exchange,提问作者Joel G Mathew
相关产品推荐
相关产品推荐

