when i send an email message like this i cant get the subject get into the message(i get it in the body). what can i do to change it? thank you!
def SendEmailNotHTML(EmailToList,EmailBody,EmailSubject):
mail_from = settings.SMTP_USER
try:
for current_mail_to in EmailToList:
fromaddr = settings.SMTP_USER
toaddrs = current_mail_to
msg = "\r\n".join([
"Subject: {0}".format(EmailSubject),
"",
"{0}".format(EmailBody)
])
print(msg)
my_email = MIMEText(msg, "plain")
username = settings.SMTP_USER
password = settings.SMTP_PASSWORD
server = smtplib.SMTP('smtp.gmail.com:25')
server.ehlo()
server.starttls()
server.login(username,password)
server.sendmail(fromaddr, toaddrs, my_email.as_string())
server.quit()
except Exception as e:
print('cant send email' + str(e))
Related
When entering a message , the console outputs that the "ms" variable is empty , how can this be fixed ?
def send_mail(id_user, message_topic):
data = read_date_json()
ms = ''
login = data['MyDate'][0]['login']
password = data['MyDate'][0]['password']
mail = data['MyDate'][0]['login'].split('#')[1]
if ('yandex' in mail) or ('ya' in mail):
ms = 'yandex.ru'
elif 'gmail' in mail:
ms = 'gmail.com'
elif 'mail' in mail:
ms = 'mail.ru'
url = data['Mail'][0][ms]
number, topic, message = message_topic.split('$')
toaddr = data['MyFriend'][0]['mail'][int(number)]
msg = MIMEMultipart()
msg['Subject'] = topic
msg['From'] = login
body = message
msg.attach(MIMEText(body, 'plain'))
try:
server = root.SMTP_SSL(url, 465)
except:
print('no connect')
server.login(login, password)
server.sendmail(login, toaddr, msg.as_string())
server.quit()
bot.send_message(id_user, 'Ваше сообщение отправлено')
I tried to overwrite variables and tried to use other mail, but to no avail
I'm using this code to send email and it works, but when I receive email the subject looks like this and also has no message:
" No subject"
afsagsag#gmail.com To: Subject: OMG Super Important Message Good morning, <afsagsag#gmail.com>
import smtplib
import carriers
def amtg():
gmail_user = 'sgfsfsfsf#gmail.com'
gmail_password = 'rtgassds'
sent_from = gmail_user
to = ['sgssfsd#gmail.com']
subject = 'OMG Super Important Message'
body = carriers.rsting + carriers.amtg1
email_text = """\
From: %s
To: %s
subject: %s
%s
""" % (sent_from, ", ".join(to), subject, body)
try:
server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
server.ehlo()
server.login(gmail_user, gmail_password)
server.sendmail(sent_from, to, email_text)
server.close()
print ('Email sent!')
except:
print ('Something went wrong...')
I have a basic python code that sends out an email to addresses from a list in Google sheet.
I want to count the number of times an email is sent to a particular email address by the python script. I tried researching on it. I didn't find anything related to it. And being a complete beginner hasn't helped me make much progress.
If anyone can point me to a particular direction that would be super helpful. Thanks so much in advance.
Below is the code
import smtplib
import ssl
from email.mime.text import MIMEText # New line
from email.utils import formataddr # New line
# User configuration
sender_email = 'email ID'
sender_name = 'name'
password = "password"
receiver_emails = [RECEIVER_EMAIL_1, RECEIVER_EMAIL_2, RECEIVER_EMAIL_3]
receiver_names = [RECEIVER_NAME_1, RECEIVER_NAME_2, RECEIVER_NAME_3]
# Email text
email_body = '''
This is a test email sent by Python. Isn't that cool?
'''
for receiver_email, receiver_name in zip(receiver_emails, receiver_names):
print("Sending the email...")
# Configurating user's info
msg = MIMEText(email_body, 'plain')
msg['To'] = formataddr((receiver_name, receiver_email))
msg['From'] = formataddr((sender_name, sender_email))
msg['Subject'] = 'Hello, my friend ' + receiver_name
try:
# Creating a SMTP session | use 587 with TLS, 465 SSL and 25
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
# Encrypts the email
context = ssl.create_default_context()
server.starttls(context=context)
# We log in into our Google account
server.login(sender_email, password)
# Sending email from sender, to receiver with the email body
server.sendmail(sender_email, receiver_email, msg.as_string())
print('Email sent!')
except Exception as e:
print(f'Oh no! Something bad happened!n {e}')
finally:
print('Closing the server...')
server.quit()
I would suggest you to create a list of successful emails, which will be populated on each iteration and then, use Counter from collections module, which receives an iterable and returns an object with number of occurrences of each element in the iterable.
You can try the following code:
from collections import Counter
import json
counter_file_path = "counter.json"
try:
with open(counter_file_path, "r") as f:
email_stats = json.load(f)
except FileNotFoundError as ex:
email_stats = {}
successful_emails = []
for receiver_email, receiver_name in zip(receiver_emails, receiver_names):
print("Sending the email...")
# Configurating user's info
msg = MIMEText(email_body, 'plain')
msg['To'] = formataddr((receiver_name, receiver_email))
msg['From'] = formataddr((sender_name, sender_email))
msg['Subject'] = 'Hello, my friend ' + receiver_name
try:
# Creating a SMTP session | use 587 with TLS, 465 SSL and 25
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
# Encrypts the email
context = ssl.create_default_context()
server.starttls(context=context)
# We log in into our Google account
server.login(sender_email, password)
# Sending email from sender, to receiver with the email body
server.sendmail(sender_email, receiver_email, msg.as_string())
print('Email sent!')
if receiver_email in email_stats:
email_stats[receiver_email] += 1
else:
email_stats[receiver_email] = 1
except Exception as e:
print(f'Oh no! Something bad happened!n {e}')
finally:
print('Closing the server...')
server.quit()
print(email_stats) # output - all occurrences for each email
with open(counter_file_path, "w") as f:
json.dump(email_stats, f)
You can use this code to store/print success mail count into a JSON format.
import smtplib
import SSL
import json
import os
from email.mime.text import MIMEText # New line
from email.utils import formataddr # New line
fileName = "sendMail_count.json"
# To store data into json file.
# It will create file in datetime format.
def store_data_to_file(jsonStr):
jsonFile = open(fileName, "w")
json.dump(jsonStr, jsonFile)
print("data stored successfully")
# User configuration
sender_email = 'email ID'
sender_name = 'name'
password = "password"
receiver_emails = [RECEIVER_EMAIL_1, RECEIVER_EMAIL_2, RECEIVER_EMAIL_3]
receiver_names = [RECEIVER_NAME_1, RECEIVER_NAME_2, RECEIVER_NAME_3]
# To store the count of successful mail received by receiver with their respective email.
if not os.path.exists(fileName) or os.stat(fileName).st_size == 0:
print("File is empty or not found")
print("Creating a JSON file to store the data")
jsonFile = open(fileName, "w+")
print("a JSON file has been created with name: " + str(fileName))
success_mail_count = {}
else:
with open(fileName) as jsonFile:
success_mail_count = json.load(jsonFile)
print(success_mail_count)
# Email text
email_body = '''
This is a test email sent by Python. Isn't that cool?
'''
for receiver_email, receiver_name in zip(receiver_emails, receiver_names):
count = 0
print("Sending the email to..." + receiver_email)
# Configurating user's info
msg = MIMEText(email_body, 'plain')
msg['To'] = formataddr((receiver_name, receiver_email))
msg['From'] = formataddr((sender_name, sender_email))
msg['Subject'] = 'Hello, my friend ' + receiver_name
try:
# Creating a SMTP session | use 587 with TLS, 465 SSL and 25
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
# Encrypts the email
context = ssl.create_default_context()
server.starttls(context=context)
# We log in into our Google account
server.login(sender_email, password)
# Sending email from sender, to receiver with the email body
server.sendmail(sender_email, receiver_email, msg.as_string())
# Check if recevier is already present in the dict,
# then add 1 to its current count
if receiver_email in success_mail_count:
success_mail_count[receiver_email] = str(int(success_mail_count[receiver_email]) + 1)
# If reciever isn't present in map then create new entry for receiver and
# Update the count with one for successfull mail sent.
else:
success_mail_count[receiver_email] = str(count + 1)
print('Email sent!')
except Exception as e:
print(f'Oh no! Something bad happened!n {e}')
finally:
print('Closing the server...')
server.quit()
print(success_mail_count)
store_data_to_file(success_mail_count)
run this code and it will create data into file and then it will read data from file itself.
I have a class sendmail and I am trying to call it in other classes.The argument will determine which email to send. The argument in the sendmail class will send mail according to parameters given to it from other classes where it is being called.However,when executing it, I get error message saying argument not defined.
Here is my code:
#!/usr/bin/python
import smtplib
class sendmail(argument):
TO = 'yourmail#gmail.com'
if argument=='PIR':
SUBJECT = 'PIR'
TEXT = 'Motion is detected'
gmail_sender = 'mymail#gmail.com'
gmail_passwd = 'mypwd'
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.ehlo
server.login(gmail_sender, gmail_passwd)
BODY = '\r\n'.join([
'TO: %s' % TO,
'From: %s' % gmail_sender ,
'Subject: %s' % SUBJECT ,
'',
TEXT
])
try:
server.sendmail(gmail_sender, [TO], BODY)
print 'email sent'
except:
print 'error'
server.quit()
I think what you're looking for is a static function.
import smtplib
class MailUtils:
#staticmethod
def sendmail(argument):
TO = 'yourmail#gmail.com'
if argument=='PIR':
SUBJECT = 'PIR'
TEXT = 'Motion is detected'
gmail_sender = 'mymail#gmail.com'
gmail_passwd = 'mypwd'
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.ehlo
server.login(gmail_sender, gmail_passwd)
BODY = '\r\n'.join([
'TO: %s' % TO,
'From: %s' % gmail_sender ,
'Subject: %s' % SUBJECT ,
'',
TEXT
])
try:
server.sendmail(gmail_sender, [TO], BODY)
print 'email sent'
except:
print 'error'
server.quit()
You would use it by doing this:
import MailUtils
MailUtils.sendmail(argument)
Note: As mentioned in the comments below, this approach works best if the class contains multiple related functions, not just a single one.
I'm trying to email multiple recipients using the pyton script below. I've searched the forum for answers, but have not been able to implement any of them correctly. If anyone has a moment to review my script and spot/resolve the problem it would be greatly appreciated.
Here's my script, I gather my issue is in the 'sendmail' portion, but can't figure out how to fix it:
gmail_user = "sender#email.com"
gmail_pwd = "sender_password"
recipients = ['recipient1#email.com','recipient2#email.com']
def mail(to, subject, text, attach):
msg = MIMEMultipart()
msg['From'] = gmail_user
msg['To'] = ", ".join(recipients)
msg['Subject'] = subject
msg.attach(MIMEText(text))
part = MIMEBase('application', 'octet-stream')
part.set_payload(open(attach, 'rb').read())
Encoders.encode_base64(part)
part.add_header('Content-Disposition',
'attachment; filename="%s"' % os.path.basename(attach))
msg.attach(part)
mailServer = smtplib.SMTP("smtp.gmail.com", 587)
mailServer.ehlo()
mailServer.starttls()
mailServer.ehlo()
mailServer.login(gmail_user, gmail_pwd)
mailServer.sendmail(gmail_user, to, msg.as_string())
mailServer.close()
mail("recipient1#email.com, recipient2#email.com",
"Subject",
"Message",
"attchachment")
Any insight would be greatly appreciated.
Best,
Matt
It should be more like
mail(["recipient1#email.com", "recipient2#email.com"],
"Subject",
"Message",
"attchachment")
You already have a array of recipients declared,that too globally,You can use that without passing it as an argument to mail.
I wrote this bit of code to do exactly what you want. If you find a bug let me know (I've tested it and it works):
import email as em
import smtplib as smtp
import os
ENDPOINTS = {KEY: 'value#domain.com'}
class BoxWriter(object):
def __init__(self):
pass
def dispatch(self, files, box_target, additional_targets=None, email_subject=None, body='New figures'):
"""
Send an email to multiple recipients
:param files: list of files to send--requires full path
:param box_target: Relevant entry ENDPOINTS dict
:param additional_targets: other addresses to send the same email
:param email_subject: optional title for email
"""
destination = ENDPOINTS.get(box_target, None)
if destination is None:
raise Exception('Target folder on Box does not exist')
recipients = [destination]
if additional_targets is not None:
recipients.extend(additional_targets)
subject = 'Updating files'
if email_subject is not None:
subject = email_subject
message = em.MIMEMultipart.MIMEMultipart()
message['From'] = 'user#domain.com'
message['To'] = ', '.join(recipients)
message['Date'] = em.Utils.formatdate(localtime=True)
message['Subject'] = subject
message.attach(em.MIMEText.MIMEText(body + '\n' +'Contents: \n{0}'.format('\n'.join(files))))
for f in files:
base = em.MIMEBase.MIMEBase('application', "octet-stream")
base.set_payload(open(f, 'rb').read())
em.Encoders.encode_base64(base)
base.add_header('Content-Disposition', 'attachment; filename={0}'.format(os.path.basename(f)))
message.attach(base)
conn = smtp.SMTP('smtp.gmail.com', 587)
un = 'user#gmail.com'
pw = 'test1234'
conn.starttls()
conn.login(un, pw)
conn.sendmail('user#domain.com', recipients, message.as_string())
conn.close()
I was facing the same issue, I fixed this issue now. Here is my code -
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import smtplib
import datetime
def sendMail():
message = MIMEMultipart()
message["To"] = "xxxxx#xxxx.com,yyyy#yyyy.com"
message["Cc"] = "zzzzzz#gmail.com,*********#gmail.com"
message["From"] = "xxxxxxxx#gmail.com"
message["Password"] = "***************"
server = 'smtp.gmail.com:587'
try:
now = datetime.datetime.now()
message['Subject'] = "cxxdRL Table status (Super Important Message) - "+str(now)
server = smtplib.SMTP(server)
server.ehlo()
server.starttls()
server.login(message["From"], message["Password"])
server.sendmail(message["From"], message["To"].split(",") + message["Cc"].split(","), message.as_string())
server.quit()
print('Mail sent')
except:
print('Something went wrong...')
sendMail()