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())
Related
I am automating the sending of emails by iterating over a DataFrame but after many iterations have this error 'smtplib.SMTPServerDisconnected', I don't know what I can do to solve this problem.
My code is:
import pandas as pd
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
filename="my_excel.xlsx"
df=pd.read_excel(filename, sheet_name='Sheet1')
user = 'my_mail'
app_password = 'password'
host = 'smtp.gmail.com'
port = 465
subject = 'Proof'
attachment = "attachment.pdf"
while i<=len(df):
if df['Status'][i]=='vencido':
text='my_text'
to = df['email'][i]
message = MIMEMultipart()
message['From'] = Header(user)
message['To'] = Header(to)
message['Subject'] = Header(subject)
content_txt= text
message.attach(MIMEText(content_txt, 'plain', 'utf-8'))
att_name = os.path.basename(attachment)
att1 = MIMEText(open(attachment, 'rb').read(), 'base64', 'utf-8')
att1['Content-Type'] = 'application/octet-stream'
att1['Content-Disposition'] = 'attachment; filename=' + att_name
message.attach(att1)
server = smtplib.SMTP_SSL(host, port)
server.login(user, app_password)
server.sendmail(user, to, message.as_string())
server.quit()
Trying to write a simple code to send out emails to one receiver and 2 other recipients. The issue is that when I put cc in server.sendmail(email, (send_to_email + cc), text). It gives me the error TypeError: can only concatenate str (not "list") to str. If I remove cc from server.sendmail(email, send_to_email, text) and run the code, my receiver gets the mail and shows the other 2 CC mails in the email but the 2 CC recipients do not get the mail. Any help?
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
cc = ['1mail#gmail.com','2mail#gmail.com']
email = "botemail#gmail.com" # the email where you sent the email
password = 'password123'
send_to_email = 'mymail#gmail.com' # for whom
subject = "Status BOT"
message = "Could not login"
print("Sending email to", send_to_email)
msg = MIMEMultipart()
msg["From"] = email
msg["To"] = send_to_email
msg['Cc'] = ', '.join(cc)
msg["Subject"] = subject
msg.attach(MIMEText(message, 'plain'))
server = smtplib.SMTP("smtp.gmail.com", 587)
server.starttls()
server.login(email, password)
text = msg.as_string()
server.sendmail(email, (send_to_email + cc), text)
server.quit()
You are on the right track
The issue here is you are trying to concat a str send_to_email with a list cc
You can change the send_to_email as a list and it should work fine
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
cc = ['1mail#gmail.com','2mail#gmail.com']
email = "botemail#gmail.com" # the email where you sent the email
password = 'password123'
send_to_email = ['mymail#gmail.com'] # for whom #### CHANGED HERE
subject = "Status BOT"
message = "Could not login"
print("Sending email to", send_to_email)
msg = MIMEMultipart()
msg["From"] = email
msg["To"] = send_to_email
msg['Cc'] = ', '.join(cc)
msg["Subject"] = subject
msg.attach(MIMEText(message, 'plain'))
server = smtplib.SMTP("smtp.gmail.com", 587)
server.starttls()
server.login(email, password)
text = msg.as_string()
server.sendmail(email, (send_to_email + cc), text)
server.quit()
Manage to fix the issue.
msg["From"] = email
msg["To"] = ', '.join(send_to_email)
msg['Cc'] = ', '.join(cc)
msg["Subject"] = subject
I am working on a python script to send email to my customer with a survey. I will send only one email with all my customers's emails in the BCC field so that I do not need to loop through all the emails. Everything works fine when I tested sending emails to my company's coleagues and also when I sent to my personal email, but whenever I send to a gmail account, the BCC field appears to not be hidden and show all the emails. I found this post Email Bcc recipients not hidden using Python smtplib and tried that solution as well, but as I am using a html body email, the emails were shown inside the body. Can anyone help me on this one?
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
def send_survey_mail():
template_path = 'template.html'
background_path = 'image.png'
button_path = 'image2.png'
try:
body = open(template_path, 'r')
msg = MIMEMultipart()
msg['Subject'] = 'Customer Survey'
msg['To'] = ', '.join(['myemail#domain.com.br', 'myemail2#domain.com'])
msg['From'] = 'mycompany#mycompany.com.br'
msg['Bcc'] = 'customer#domain.com'
text = MIMEText(body.read(), 'html')
msg.attach(text)
fp = open(background_path, 'rb')
img = MIMEImage(fp.read())
fp.close()
fp2 = open(button_path, 'rb')
img2 = MIMEImage(fp2.read())
fp2.close()
img.add_header('Content-ID', '<image1>')
msg.attach(img)
img2.add_header('Content-ID', '<image2>')
msg.attach(img2)
s = smtplib.SMTP('smtpserver')
s.sendmail('mycompany#mycompany.com.br',
['myemail#domain.com.br', 'myemail2#domain.com', 'customer#domain.com'],
msg.as_string())
s.quit()
except Exception as ex:
raise ex
send_survey_mail()
I removed the following line from the code and tried again. Now the email is not sent to my customer's Gmail email.
msg['Bcc'] = 'customer#gmail.com'
Just do not mention bcc mails in msg['To'] or msg['Cc']. Do it only in server.sendmail()
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
from_addr = "your#mail.com"
to_addr = ["to#mail.com", "to2#mail.com"]
msg = MIMEMultipart()
msg['From'] = from_addr
msg['To'] = to_addr
msg['Subject'] = "SUBJECT"
body = "BODY"
msg.attach(MIMEText(body, 'plain'))
filename = "FILE.pdf"
attachment = open('/home/FILE.pdf', "rb")
part = MIMEBase('application', 'octet-stream')
part.set_payload((attachment).read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', "attachment; filename= %s" % filename)
msg.attach(part)
server = smtplib.SMTP('.....', 587)
server.starttls()
server.login(from_addr, 'yourpass')
text = msg.as_string()
server.sendmail(from_addr, to_addr + [bcc#mail.com], text)
server.quit()
Did you try not to define the msg['BCC'] field? Setting this field forces it to be included. It is sufficient that the BCC email address is in the sendmail command's destination address list. Take a look at this question.
MAIL_FROM = default#server.com
MAIL_DL = default#server.com
def send(to, cc, bcc, subject, text, html):
message = MIMEMultipart("alternative")
message["Subject"] = subject
message["From"] = MAIL_FROM
message["To"] = to
message["Cc"] = cc + "," + MAIL_DL
if html is not None:
body = MIMEText(html, "html")
else:
body = MIMEText(text)
message.attach(body)
server = smtplib.SMTP(MAIL_SERVER)
server.set_debuglevel(1)
server.sendmail(MAIL_DL, to.split(",") + bcc.split(","), message.as_string())
server.quit()
return {
"to": to,
"cc": cc,
"bcc": bcc,
"subject": subject,
"text": text,
"html": html,
}
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()
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