Python email script not sending through Gmail SMTP

I’m having trouble with a Python script that’s supposed to send emails via Gmail’s SMTP server. Here’s what I’ve got:

import email_sender

message = 'Test email content.'

connection = email_sender.connect('smtp.gmail.com', 587)
connection.start_secure()
connection.login('[email protected]', 'password123')
connection.send('[email protected]', '[email protected]', message)
connection.end()

I’ve tried running this on two different web hosts but no luck. One host gives me a ‘connection refused’ error while the other doesn’t show any errors but the email never arrives.

I turned on debug mode and the output suggests the message was sent successfully but I never receive it. Any ideas what could be going wrong? Could it be a problem with the web hosts or is there something off in my code?

From my experience, the issue might not be with your code, but rather with Gmail’s security measures. Google has become increasingly strict about SMTP access, especially from unfamiliar IP addresses or devices.

I’d suggest using OAuth2 for authentication instead of your account password. This method is more secure and less likely to be blocked by Gmail. You’ll need to set up credentials in the Google Cloud Console and modify your script to use the OAuth2 flow.

If you’re not keen on OAuth2, another option is to use Google’s App Passwords feature. Generate an app-specific password for your script in your Google Account settings. This bypasses two-factor authentication and some other security checks.

Lastly, ensure your account doesn’t have any security alerts or restrictions. Sometimes, Google may temporarily limit SMTP access if it detects unusual activity.

I’ve encountered similar issues with Gmail SMTP before. In my case, I noticed that Gmail may block what it considers insecure connections. Enabling “Less secure app access” in your Google account settings can often resolve this, as Gmail is cautious with scripts attempting to send emails.

Another approach that worked for me was setting up an app-specific password, which can help by avoiding issues with the main account credentials.

Additionally, it’s important to check if your web host is blocking outgoing SMTP traffic since some hosts restrict this as a measure against spam. Verifying that your recipient’s email address is correct and reviewing any spam filters can also prove helpful.

hey, have u tried using app passwords? i had similar probs n that worked for me. go to ur google account settings, look for ‘app passwords’ n generate one for ur script. replace ur regular password with that in the code. also, check if ur host allows outgoing smtp traffic. some block it to prevent spam.