0

I want to generate email contents on the fly and send email from a Gmail account using Python from an EC2 server. It works fine when I do it on localhost, but when I run the same code on my EC2, it doesn't work...

Here is my code:

from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
msg = MIMEMultipart()

part = MIMEApplication(file("<pathtopdf>").read())
part.add_header('Content-Disposition', 'attachment; filename="<nameofpdf.pdf>"')
msg.attach(part)

msg['From'] = "<username>@gmail.com"
msg['To'] = "<username>@gmail.com"
msg['Subject'] = "Hello PDF"
import smtplib 
server = smtplib.SMTP('smtp.gmail.com',587) #port 465 or 587
server.ehlo()
server.starttls()
server.ehlo()
server.login(<login info params>)
server.close()

Is there anyway to do this without using Amazon SES? I only have to send an email upon customer request, and I just have to generate a quick PDF based on customer input and send an email to the customer at the email they specify to send to... it's a very simple operation and the hoops I have to jump through are getting a tad frustrating.

Adeel Ahmad
  • 1,033
  • 1
  • 11
  • 24
mnot
  • 161
  • 1
  • 4
  • 16
  • 1
    `it doesn't work` means nothing to others. Where exactly does it fail? – helloV Jun 29 '17 at 05:12
  • You could use Python to send a notification to AWS' `SNS` service, which can then send an email to a recipient as desired. – Henry Jun 29 '17 at 08:32

2 Answers2

1

You have to enable port 587 in outbound rules.

Duwa
  • 76
  • 4
0

EDIT

I recommend you to use AWS SES. Because Gmail blocks EC2 IP addresses.

Gmail SMTP is not working in ec2 instance

hiropon
  • 1,675
  • 2
  • 18
  • 41
  • How do I go about configuring an elastic IP? And why would I have to do that? – mnot Jun 29 '17 at 05:06
  • @mnot Sorry, I changed my thought. Please read this link: https://stackoverflow.com/questions/21087564/gmail-smtp-is-not-working-in-ec2-instance – hiropon Jun 29 '17 at 05:16
  • I believe you are premature in answering this question, @hiropon, because OP hasn't yet explained what "it doesn't work" means. This appears to be an authenticated SMTP (MSA) transaction, so for google to block access by IP doesn't really make sense. – Michael - sqlbot Jun 29 '17 at 08:19