Hello beauful people , i hope your day is doing awesome
I have a text file with my marketing emails list seperated with lines
like this : example1#gmail.com example2#yahoo.com example#hotmail.com
and i have 4 smtp server linked to my cpanel from i send my marketing
emails !!
Well i can import smtps from file to my code and it connects to the
first smtp in the list and starts sending and when one smtp is down
or timeout it goes to the next smtp BUT starting from the top of
the mail list again ,it does not continue from where the first smtp
stopped in the mail list .
This is from my code :
Function to grab my smtps from text file :
def checker(file):
with open(file, "r") as f:
lines = f.readlines()
for line in lines:
smtp_server, smtp_port, smtp_user, smtp_pass = line.rstrip('\n').split("|")
Function to generate message for every email :
def generate_messages(recipients):
with open(letter_path, 'r', encoding='utf-8') as myfile:
data = myfile.read()
for recipient in recipients:
message = EmailMessage()
message['Subject'] = letter_subject
message['From'] = Address(letter_From, *smtp_user.split("#"))
message['To'] = recipient
message.set_content(data, 'html')
yield message
Function of sending
def smtp(smtp_server, port, user, password, messages):
with smtplib.SMTP(smtp_server, port) as server:
try:
server.ehlo()
server.starttls()
server.ehlo()
server.login(user, password)
print(crayons.green(f'Connected to smtp : {smtp_server}\n'''))
for message in messages:
server.send_message(message)
print(Fore.GREEN +'\n[+]', message['To'] + f''' SENT!{time.strftime('%X')}''')
time.sleep(10)
except smtplib.SMTPException:
print(crayons.red(f'''smtp died \nSERVER : {smtp_server}\n'''))
i have thought about it a lot and i still can't find it how to let the
next smtp continue continue from where the first one stopped !!
thanks for your help in advance
The answer is easy apparently !!!
we just have to add
recipients.remove(recipient)
under the message['To'] = recipient
now we delete the recepient from the existance when the message is sent!
Related
I am trying to create a bulk email sender. I want the script to open form.csv that contains multiple email addresses, and send the email to them.
Problem is after sending 75 to 80 mails its give an error, total no of mail is (1000)
Simply, I need help to send more and sends the email to those addresses.
below is the src code its working fine.enter code here
import csv, smtplib, ssl
port = 587
smtp_server = "smtp.gmail.com"
login = "example#gmail.com" # paste your login
password = "jjshajcaez" # paste your password
message = """Subject: Happy New Year
To: {recipient}
From: {sender}
Dear {name},
We wish you and your family a very Happy New Year!
With warm regards, """
sender = "example#gmail.com"
context = ssl.create_default_context()
with smtplib.SMTP(smtp_server, port) as server:
server.connect('smtp.gmail.com', '587')
server.ehlo() # Can be omitted
server.starttls(context=context)
server.ehlo() # Can be omitted
server.login(login, password)
with open("form.csv") as file:
reader = csv.reader(file)
next(reader) # it skips the header row
for name, email in reader:
server.sendmail(
sender,
email,
message.format(name=name, recipient=email, sender=sender)
)
print(f'Sent to {name}')
form.csv
#name, email
Test, test#gmail.com
is there any suggestion how to modify the code... so that it can send mail at once and store the log file on the system.
I'm trying to check whether an email exists or not using Python's smtplib
This is what I did:
s = smtplib.SMTP()
s.connect(mxRecord)
s.mail('my#email.com') //Here the error shows up
The error is:
Client host [...] blocked using Spamhaus. To request removal from this list see http://www.spamhaus.org/lookup.lasso (S3130)
I tried something and it worked well.
import dns.resolver, smtplib
MyEmail = "X#hotmail.com"
MyPassword = "XXX"
EmailToValidate = "X#Y.com"
record = dns.resolver.query(str.split(EmailToValidate, "#")[1], "MX")
mx = str(record[0].exchange)
server = smtplib.SMTP("smtp.live.com", 587)
server.ehlo()
server.starttls()
server.ehlo()
server.login(MyEmail, MyPassword)
server.helo("live.com")
server.connect(mx)
server.mail(MyEmail)
code, msg = server.rcpt(EmailToValidate)
print("Code: ", str(code), " message: ", msg)
the (code, message) pair will be (250, OK) if the email exists, and (550, Address Rejected) if the email does not exists.
I wrote this on hurry, so there might be some unnecessary steps.
I could see several topics on try - catch but doesnt seem to discuss errors if any from finally block itself. I found that the error is not handled if it is in finally block. What would be the ideal way to manage finally?
For eg. below is a mail function. if there is any error in try block, finally will execute the quit method which itself is not initiated so an unhandled error occurs. So is it better to ensure there is no errors occur in finally block?
def send_email(ldap, email_address, password, msg):
try:
message = MIMEMultipart('alternative')
message['To'] = email.utils.formataddr(('Recipient', '%s#abc.com'%email_address))
message['From'] = email.utils.formataddr(('Author', '%s#abc.com'%email_address))
message['Subject'] = 'Sample subject'
text = "%s"%msg
html = MIMEText('<html><head></head><h2>data</h2><body><p>%s</p></body></html>'%msg,'html')
message.attach(html)
server = smtplib.SMTP(host="ip",port=0)
server.set_debuglevel(True)
# identify ourselves, prompting server for supported features
server.ehlo()
if server.has_extn('STARTTLS'):
server.starttls()
server.ehlo()
server.login(ldap, password)
print "%s#abc.com, %s#abc.com, %s "%(email_address,email_address,message.as_string())
server.sendmail('%s#abc.com'%email_address, "%s#abc.com"%email_address, message.as_string())
finally:
server.quit()
Dont put a bunch of code (doing different things) into one try/except block, but you can easily add an if/else condition in your finally block:
def send_email(ldap, email_address, password, msg):
server = None #make sure server variable is always defined.
try:
...
server = smtplib.SMTP(...)
...
finally:
if server and isinstance(x, smtplib.SMTP):
server.quit()
Since your finally block is only used to ensure the server connection is properly closed whatever, the obvious answer is to only wrap the relevant part in the try block:
def send_email(ldap, email_address, password, msg):
message = MIMEMultipart('alternative')
message['To'] = email.utils.formataddr(('Recipient', '%s#abc.com'%email_address))
message['From'] = email.utils.formataddr(('Author', '%s#abc.com'%email_address))
message['Subject'] = 'Sample subject'
text = "%s"%msg
html = MIMEText('<html><head></head><h2>data</h2><body><p>%s</p></body></html>'%msg,'html')
message.attach(html)
server = smtplib.SMTP(host="ip",port=0)
# now you can start the try block:
try:
server.set_debuglevel(True)
# identify ourselves, prompting server for supported features
server.ehlo()
if server.has_extn('STARTTLS'):
server.starttls()
server.ehlo()
server.login(ldap, password)
print "%s#abc.com, %s#abc.com, %s "%(email_address,email_address,message.as_string())
server.sendmail('%s#abc.com'%email_address, "%s#abc.com"%email_address, message.as_string())
finally:
server.quit()
A still better solution would be to split this code in distinct functions each with a single well-defined responsability - preparing the message, getting a connection to the server etc, ie:
def prepare_message(sender, recipient, subject, msg):
message = MIMEMultipart('alternative')
message['To'] = email.utils.formataddr(('Recipient', recipient))
message['From'] = email.utils.formataddr(('Author', sender))
message['Subject'] = subject
#text = "%s" % msg # this one is useless
html = MIMEText("""
<html>
<head></head>
<body>
<h2>data</h2>
<p>%s</p>
</body>
</html>""" % msg,
'html'
)
message.attach(html)
return message
def connect(ldap, password):
server = smtplib.SMTP(host="ip",port=0)
server.set_debuglevel(True)
# identify ourselves, prompting server for supported features
server.ehlo()
if server.has_extn('STARTTLS'):
server.starttls()
server.ehlo()
server.login(ldap, password)
return server
def send_email(ldap, email_address, password, msg):
sender = recipient = "%s#abc.com" % email_address
message = prepare_message(sender, recipient, 'Sample subject', msg)
server = connect(ldap, password)
try:
server.sendmail(sender, recipient, message.as_string())
finally:
server.quit()
could someone kindly tell me, what's wrong with the code below? TIA :)))
import smtplib
if raw_input("if you want to send a message from a gmail account, type yes: ") == 'yes':
try:
sender = raw_input("from:\n")
senders_pwd = raw_input("password:\n")
recipient = raw_input("to:\n")
print 'ok, now compile your message:'
subject = raw_input("subject:\n")
body = raw_input("your message:\n")
message = "subject: %s\n%s" %(subject,body)
server = smtplib.SMTP("smtp.gmail.com",587)
server.ehlo()
server.starttls()
server.ehlo()
print "ok, I've sent your email"
except:
print 'failed to send'
You need to call the sendmail() function. Add something like these three lines after the last server.ehlo():
server.login(sender, senders_pwd)
server.sendmail(sender, recipient, message)
server.close()
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Receive and send emails in python
I tried searching but couldn't find a simple way to send an email.
I'm looking for something like this:
from:"Test1#test.com"#email sender
To:"test2#test.com"# my email
content:open('x.txt','r')
Everything I've found is complicated really: my project doesn't need so many lines.
Please, I like to learn: leave comments in each code and explain
The docs are pretty straitforward:
# Import smtplib for the actual sending function
import smtplib
# Import the email modules we'll need
from email.mime.text import MIMEText
# Open a plain text file for reading. For this example, assume that
# the text file contains only ASCII characters.
fp = open(textfile, 'rb')
# Create a text/plain message
msg = MIMEText(fp.read())
fp.close()
# me == the sender's email address
# you == the recipient's email address
msg['Subject'] = 'The contents of %s' % textfile
msg['From'] = me
msg['To'] = you
# Send the message via our own SMTP server, but don't include the
# envelope header.
s = smtplib.SMTP()
s.sendmail(me, [you], msg.as_string())
s.quit()
import smtplib
def prompt(prompt):
return raw_input(prompt).strip()
fromaddr = prompt("From: ")
toaddrs = prompt("To: ").split()
print "Enter message, end with ^D (Unix) or ^Z (Windows):"
# Add the From: and To: headers at the start!
msg = ("From: %s\r\nTo: %s\r\n\r\n"
% (fromaddr, ", ".join(toaddrs)))
while 1:
try:
line = raw_input()
except EOFError:
break
if not line:
break
msg = msg + line
print "Message length is " + repr(len(msg))
server = smtplib.SMTP('localhost')
server.sendmail(fromaddr, toaddrs, msg)
server.quit()
A simple example, which works for me, using smtplib:
#!/usr/bin/env python
import smtplib # Brings in the smtp library
smtpServer='smtp.yourdomain.com' # Set the server - change for your needs
fromAddr='you#yourAddress' # Set the from address - change for your needs
toAddr='you#yourAddress' # Set the to address - change for your needs
# In the lines below the subject and message text get set up
text='''Subject: Python send mail test
Hey!
This is a test of sending email from within Python.
Yourself!
'''
server = smtplib.SMTP(smtpServer) # Instantiate server object, making connection
server.set_debuglevel(1) # Turn debugging on to get problem messages
server.sendmail(fromAddr, toAddr, text) # sends the message
server.quit() # you're done
This is code I found a while back at Link and modified.