Norbert
Norbert

Reputation: 435

How to send variable value via email with smtplib in python3?

I am able to send email when the message is a string directly typed into the function, but not when it is a variable.

This code works:

import smtplib

server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
server.login("[email protected]", "somepassword")

server.sendmail(
"[email protected]", 
"[email protected]", 
"a manually typed string like this")
server.quit()

But this code, with a variable string, doesn't:

import smtplib

server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
server.login("[email protected]", "somepassword")

someVariable = "any string"

server.sendmail(
"[email protected]", 
"[email protected]", 
someVariable)
server.quit()

More exactly, this second version does send an email but with an empty body. No characters show up.

How can I make the second version work?

print(someVariable) and print(type(someVariable)) give the right (expected) outputs.

Upvotes: 0

Views: 4723

Answers (3)

rogersdevop
rogersdevop

Reputation: 66

My personal experience with Office365 led me to this solution:

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

msg = MIMEMultipart()

msg['Subject'] = 'confirmation email'
msg['From'] = '[email protected]'
msg['To'] = ", ".join(['[email protected]','[email protected]'])

body = 'Example email text here.'

msg.attach(MIMEText(body, 'html')) #set to whatever text format is preferred

And then the final piece of how it fits with your current script

server.sendmail('[email protected]','[email protected]',msg.as_string())

Upvotes: 2

Norbert
Norbert

Reputation: 435

It turns out this worked, inspired by [these docs][1] and by rogersdevop's earlier answer (which didn't work for me):

def sendEmail(msge):

import smtplib
from email.mime.text import MIMEText

msg = MIMEText(msge)

me = '[email protected]'
you = '[email protected]'
msg['Subject'] = 'The subject line'
msg['From'] = me
msg['To'] = you

s = smtplib.SMTP_SSL('smtp.gmail.com', 465)
s.login("[email protected]", "somepassword")
s.send_message(msg)
s.quit()

Upvotes: 2

Reedinationer
Reedinationer

Reputation: 5774

You could try something like

import smtplib

server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
server.login("[email protected]", "somepassword")

server.sendmail(
"[email protected]", 
"[email protected]", 
"{}".format(someVariable))
server.quit()

I imagine that you just need to format whatever the variable is into a string

Upvotes: 0

Related Questions