Sending emails with smtp python, problem with def block - python

I'm new to python, I'm working with python 3. I need to send an email with generated message. Everything is ok with message (I can print it) but somehow in that configuration, with that def-blocks emails aren't sent. What am I doing wrong? I don't get any error notifications.
import random
import string
import smtplib
port = 2525
smtp_server = "smtp.mailtrap.io"
login = "my mailtrap login"
password = "my mailtrap pass"
sender = "from#smtp.mailtrap.io"
receiver = "to#smtp.mailtrap.io"
def randomString(stringLength=10):
letters = string.ascii_lowercase
return ''.join(random.choice(letters) for i in range(stringLength))
def randomMessage():
random_string1 = randomString()
random_string2 = randomString()
message = f"""\
Subject: {random_string1}
To: {receiver}
From: {sender}
{random_string2}"""
return message
def main():
with smtplib.SMTP(smtp_server, port) as server:
server.login(login, password)
message = randomMessage()
#print(message)
server.sendmail(sender, receiver, message)
if __name__ == '__main__':
main()

Problem was in message type. I changed it to MIMEText and it works now.
import random
import string
import smtplib
from email.mime.text import MIMEText
port = 2525
smtp_server = "smtp.mailtrap.io"
login = "my mailtrap login"
password = "my mailtrap pass"
sender = "from#smtp.mailtrap.io"
receiver = "to#smtp.mailtrap.io"
def randomString(stringLength=10):
lettersDigits = string.ascii_lowercase + "0123456789"
return ''.join(random.choice(lettersDigits) for i in range(stringLength))
def makeMessage(subject, content):
message = MIMEText(content)
message["Subject"] = subject
message["From"] = sender
message["To"] = receiver
return message
def randomMessage():
return makeMessage(randomString(), randomString())
def sendMessage(message):
with smtplib.SMTP(smtp_server, port) as server:
server.login(login, password)
server.sendmail(sender, receiver, message.as_string())

Related

send mail python asyncio

I'm trying to learn asyncio. If I run this program normally without the asyncio library than it takes less time while it takes more time in this way so is this the right way to send mail using asyncio or there is any other way?
import smtplib
import ssl
import time
import asyncio
async def send_mail(receiver_email):
try:
print(f"trying..{receiver_email}")
server = smtplib.SMTP(smtp_server, port)
server.ehlo()
server.starttls(context=context)
server.ehlo()
server.login(sender_email, password)
message = "test"
await asyncio.sleep(0)
server.sendmail(sender_email, receiver_email, message)
print(f"done...{receiver_email}")
except Exception as e:
print(e)
finally:
server.quit()
async def main():
t1 = time.time()
await asyncio.gather(
send_mail("test#test.com"),
send_mail("test#test.com"),
send_mail("test#test.com"),
send_mail("test#test.com")
)
print(f"End in {time.time() - t1}sec")
if __name__ == "__main__":
smtp_server = "smtp.gmail.com"
port = 587 # For starttls
sender_email = "*****"
password = "*****"
context = ssl.create_default_context()
asyncio.run(main())
You are not really doing sending your emails correctly using asyncio. You should be using the aiosmtplib for making asynchronous SMTP calls such as connect, starttls, login, etc. See the following example, which I have stripped down from a more complicated program that handled attachments. This code sends two emails asynchronously:
#!/usr/bin/env python3
import asyncio
import aiosmtplib
import sys
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
MAIL_PARAMS = {'TLS': True, 'host': 'xxxxxxxx', 'password': 'xxxxxxxx', 'user': 'xxxxxxxx', 'port': 587}
async def send_mail_async(sender, to, subject, text, textType='plain', **params):
"""Send an outgoing email with the given parameters.
:param sender: From whom the email is being sent
:type sender: str
:param to: A list of recipient email addresses.
:type to: list
:param subject: The subject of the email.
:type subject: str
:param text: The text of the email.
:type text: str
:param textType: Mime subtype of text, defaults to 'plain' (can be 'html').
:type text: str
:param params: An optional set of parameters. (See below)
:type params; dict
Optional Parameters:
:cc: A list of Cc email addresses.
:bcc: A list of Bcc email addresses.
"""
# Default Parameters
cc = params.get("cc", [])
bcc = params.get("bcc", [])
mail_params = params.get("mail_params", MAIL_PARAMS)
# Prepare Message
msg = MIMEMultipart()
msg.preamble = subject
msg['Subject'] = subject
msg['From'] = sender
msg['To'] = ', '.join(to)
if len(cc): msg['Cc'] = ', '.join(cc)
if len(bcc): msg['Bcc'] = ', '.join(bcc)
msg.attach(MIMEText(text, textType, 'utf-8'))
# Contact SMTP server and send Message
host = mail_params.get('host', 'localhost')
isSSL = mail_params.get('SSL', False);
isTLS = mail_params.get('TLS', False);
port = mail_params.get('port', 465 if isSSL else 25)
smtp = aiosmtplib.SMTP(hostname=host, port=port, use_tls=isSSL)
await smtp.connect()
if isTLS:
await smtp.starttls()
if 'user' in mail_params:
await smtp.login(mail_params['user'], mail_params['password'])
await smtp.send_message(msg)
await smtp.quit()
if __name__ == "__main__":
email = "xxxxxxxx";
co1 = send_mail_async(email,
[email],
"Test 1",
'Test 1 Message',
textType="plain")
co2 = send_mail_async(email,
[email],
"Test 2",
'Test 2 Message',
textType="plain")
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.gather(co1, co2))
loop.close()

Why email is not being send to CC list?

I have the following code where the Cc email list is not working meaning emails are not received to the folks/groups in Cc list,email to To list is working,I just can't figure out what is wrong?any guidance on how to debug and fix it?
import time,smtplib
import pprint,logging,os,time,json
from subprocess import Popen, PIPE, call
from pprint import pprint
from email.mime.text import MIMEText
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
email = 'username2#company.com'
gerriturl = ""
def sendEmail2(type,data):
global originalchange
global gerriturl,email,username1
body = '''%s''' % (data)
#msg = MIMEMultipart(body)
msg = MIMEMultipart()
sender = 'techci#company.com'
receivers = []
cc = ['username1#company.com']
REPLY_TO_ADDRESS = 'embedded-tech-integrators#group.company.com'
if type =='failure':
print("Inside failure email %s"%email)
b = '\U0001F6A8'
print("b.decode('unicode-escape')")
receivers.append('username2#company.com')
#receivers.append(email)
print('%s'%receivers)
msg['Subject'] = '%s AUTO FAILED FOR GERRIT %s :PLEASE TAKE IMMEDIATE ACTION!!!'%(b.decode('unicode-escape'),gerriturl)
msg['From'] = sender
msg['To'] = ', '.join(receivers)
msg['Cc'] = ', '.join(cc)
msg["Content-Type"] = "text/html"
try:
mail = smtplib.SMTP('relay.company.com', 25)
msg.attach(MIMEText(body, 'html'))
msg.add_header('reply-to', REPLY_TO_ADDRESS)
print('Email sent successfully %s %s'%(receivers,cc))
except Exception as e:
logger.error('Problem sending email')
logger.error('%s' % e)
def main():
data = "THIS IS A TEST EMAIL"
sendEmail2('failure',data)
if __name__ == "__main__":
main()
The important thing is to pass the complete list of recipient email addresses to the sendmail() method - you need to concatenate the email addresses for the To, CC and BCC fields into a single list, not a string.
import smtplib
def send_email(subject, body_text, emails_to, emails_cc=[], emails_bcc=[]):
# Configuration
host = "localhost"
port = 1025
from_addr = "nobody#somewhere.com"
# Build the email body
body = "\r\n".join([
"From: %s" % from_addr,
"To: %s" % ', '.join(emails_to),
"CC: %s" % ', '.join(emails_cc),
"Subject: %s" % subject ,
"",
body_text
])
# Prepare the complete list of recipient emails for the message envelope
emails = emails_to + emails_cc + emails_bcc
# Connect to the server
server = smtplib.SMTP(host, port)
# Send the email
server.sendmail(from_addr, emails, body)
# Close the server connection
server.quit()

How can I send email to multi addresses by smtplib?

I use bellow code I can send email to one account, but how can I send to multi account?
import smtplib
from email.mime.text import MIMEText
_user = "67676767#qq.com" #
_pwd = "orjxywulscbxsdwbaii" #
_to = linux213#126.com" #
msg = MIMEText("content") #
msg["Subject"] = "邮件主题测试" #
msg["From"] = _user
msg["To"] = _to
try:
s = smtplib.SMTP_SSL("smtp.qq.com", 465)
s.login(_user, _pwd)
s.sendmail(_user, _to, msg.as_string())
s.quit()
print ("Success!")
except smtplib.SMTPException as e:
print ("Falied,%s" % e)
Try this:
import smtplib
from email.mime.text import MIMEText
s = smtplib.SMTP('smtp.qq.com')
s.set_debuglevel(1)
msg = MIMEText("""body""")
sender = 'me#example.com'
recipients = ['k.ankur#abc.com', 'a.smith#abc.co.in']
msg['Subject'] = "subject line"
msg['From'] = sender
msg['To'] = ", ".join(recipients)
s.sendmail(sender, recipients, msg.as_string())

Send an email with SMTP in Python

I'm working on a project of making my own Instant-Messaging program, even without graphics or anything, just to get to know the built-in modules in python.
Here, I tried to write a code that the user will input the username and password the user wants, and then a e-mail will be sent (to the user), that will contain a 12-character random string, and the user will input it back to the program. Somehow, when I run the code my whole computer freezes!
Here's the code:
import smtplib
SMTPServer = smtplib.SMTP("smtp.gmail.com",587)
SMTPServer.starttls()
SMTPServer.login(USERNAME, PASSWORD)*
userEmail = raw_input("Please enter your e-mail: ")
if verifyEmail(userEmail) == False:
while True:
userEmail = raw_input("Error! Please enter your e-mail: ")
if verifyEmail(userEmail) == True:
break
randomString = generateRandomString()
message = """From: From Person <%s>
To: To Person <%s>
Subject: Ido's IM Program Registration
Your registration code is: %s
""" %(SERVEREMAIL, userEmail, randomString)
try:
smtpObj = smtplib.SMTP('localhost')
smtpObj.sendmail(SERVEREMAIL, userEmail, message)
print "Successfully sent email"
except smtplib.SMTPException:
print "Error: unable to send email"
inputString = raw_input("Input generated code sent: ")
This is a working example of a smtp client.
where does your code block?
# -*- coding: utf-8 -*-
import smtplib
from email.mime.text import MIMEText
class SMTPClient(object):
def __init__(self, recepient, subject, body):
self.recepient = recepient
self.subject = subject
self.body = body
self.mail_host = conf.get('smtp_server.host')
self.mail_port = conf.get('smtp_server.port')
self.username = conf.get('account.username')
self.password = conf.get('account.password')
self.mail_sender = conf.get('account.from')
self._setup()
def _setup(self):
self.smtp_client = smtplib.SMTP(self.mail_host, self.mail_port)
self.smtp_client.ehlo_or_helo_if_needed()
self.smtp_client.starttls()
self.smtp_client.login(self.username, self.password)
self._send_mail()
def _make_mail(self):
message = MIMEText(self.body, _charset='utf-8')
message['From'] = self.mail_sender
message['To'] = self.recepient
message['Subject'] = self.subject
return message.as_string()
def send_mail(self):
self.smtp_client.sendmail(self.mail_sender, self.recepient, self._make_mail())
self.smtp_client.quit()
This works for me!
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email import Encoders
gmail_user = 'example#hotmail.com'
gmail_pwd = 'somepassword'
subject = 'HEY'
text = 'Some text here'
msg = MIMEMultipart()
msg['From'] = gmail_user
msg['To'] = gmail_user
msg['Subject'] = subject
msg.attach(MIMEText(text))
part = MIMEBase('application', 'octet-stream')
Encoders.encode_base64(part)
mailServer = smtplib.SMTP("smtp.live.com", 587)
mailServer.ehlo()
mailServer.starttls()
mailServer.ehlo()
mailServer.login(gmail_user, gmail_pwd)
mailServer.sendmail(gmail_user,gmail_user, msg.as_string())
mailServer.close()

send mail using python

Problem: when i send mail to user then from user name not seen in to user inbox only show email-id but i need user name of sender
from: demo#gmail.com username: Demo
To: demotest#gmail.com
CODE
import smtplib
fromaddr = From
toaddrs = To
msg = 'Why,Oh why!'
username = From
password = *******
server = smtplib.SMTP('smtp.gmail.com:587')
server.ehlo()
server.starttls()
server.login(username, password)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()
smtplib does not include automatically any header, and you need to include a From: header, so you have to put one by yourself doing something like:
# Add the From: and To: headers at the start!
msg = ("From: %s\r\nTo: %s\r\n\r\n"
% (fromaddr, ", ".join(toaddrs)))
As you can se in the DOCS.
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
fromaddr = 'demo#gmail.com'
toaddrs = 'demotest#gmail.com'
msg = MIMEMultipart('alternative')
msg['Subject'] = "Link"
msg['From'] = "good morning" #like name
msg['To'] = "GGGGGG"
body = MIMEText("example email body")
msg.attach(body)
username = 'demo#gmail.com'
password = ''
server = smtplib.SMTP_SSL('smtp.googlemail.com', 465)
server.login(username, password)
server.sendmail(fromaddr, toaddrs, msg.as_string())
server.quit()
You just need to create the message correctly. I think the most convenient way to do it is using a special object for message. I placed a class which perhaps may help you to send messages in your project.
import os
import smtplib
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
class EmailSender(object):
def __init__(self, subject, to, config):
self.__subject = subject
self.__to = tuple(to) if hasattr(to, '__iter__') else (to,)
self.__from = config['user']
self.__password = config['password']
self.__server = config['server']
self.__port = config['port']
self.__message = MIMEMultipart()
self.__message['Subject'] = self.__subject
self.__message['From'] = self.__from
self.__message['To'] = ', '.join(self.__to)
def add_text(self, text):
self.__message.attach(
MIMEText(text)
)
def add_image(self, img_path, name=None):
if name is None:
name = os.path.basename(img_path)
with open(img_path, 'rb') as f:
img_data = f.read()
image = MIMEImage(img_data, name=name)
self.__message.attach(image)
def send(self):
server = smtplib.SMTP_SSL(self.__server, self.__port)
server.login(self.__from, self.__password)
server.sendmail(self.__from, self.__to, self.__message.as_string())
server.close()
sender = EmailSender("My letter", "my_target#email", {
'user': "from#email",
'password': "123456",
'server': "mail.google.com"
'port': 465
})
sender.add_text("Why,Oh why!")
sender.send()
Or go the easy way, by install yagmail and
Given:
To = 'someone#gmail.com'
From = 'me#gmail.com'
pwd = '******'
alias = 'someone'
Run:
import yagmail
yag = yagmail.SMTP(From, pwd)
yag.send({To: alias}, 'subject', 'Why,Oh why!')
Install might be done by pip install yagmail

Categories