Python 3: sending emails through any online webmail service - email

what sort of python script/function/library would allow you to send emails through any webmail service, be it gmail, yahoo, hotmail, email from your own domain etc.?
I found several examples relating to the single cases (mostly gmail), but not an all-encompassing solution.
Ex.: user inputs username, password, webmail service, then can send an email from within the python program.
Thanks.

Well, you can see some examples of how to do it here: http://docs.python.org/3/library/email-examples.html
Otherwise, you can try this:
from smtplib import SMTP_SSL as SMTP
import logging, logging.handlers, sys
from email.mime.text import MIMEText
def send_message():
text = '''
Hello,
This is an example of how to use email in Python 3.
Sincerely,
My name
'''
message = MIMEText(text, 'plain')
message['Subject'] = "Email Subject"
my_email = 'your_address#email.com'
# Email that you want to send a message
message['To'] = my_email
try:
# You need to change here, depending on the email that you use.
# For example, Gmail and Yahoo have different smtp. You need to know what it is.
connection = SMTP('smtp.email.com')
connection.set_debuglevel(True)
# Attention: You can't put for example: 'your_address#email.com'.
# You need to put only the address. In this case, 'your_address'.
connection.login('your_address', 'your_password')
try:
#sendemail(<from address>, <to address>, <message>)
connection.sendmail(my_email, my_email, message.as_string())
finally:
connection.close()
except Exception as exc:
logger.error("Error sending the message.")
logger.critical(exc)
sys.exit("Failure: {}".format(exc))
if __name__ == "__main__":
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
ch.setFormatter(formatter)
logger.addHandler(ch)
send_message()

You can send E-Mails via any webmail (that supports SMTP) with the smtplib module. That looks like this:
import smtplib
import getpass
servername = input("Please enter you mail server: ")
username = input("Please enter your username: ")
password = getpass.getpass() # This gets the password without echoing it on the screen
server = smtplib.SMTP(servername)
server.login(username, password) # Caution this now uses plain connections
# Read the documentations to see how to use SSL
to = input("Enter your destination address: ")
msg = input("Enter message: ")
message = "From: {0}#{1}\r\nTo: {2}\r\n\r\n{3}".format(username, servername, to, msg)
server.sendmail(username+"#"+servername, to, message)
server.quit
Please note that this example is neither clean nor tested. Look at the documentation for more information. Also it is very likely that you need to adjust a lot of stuff depending on the server you want to connect with.
For creating the message it's a good idea to look at the email module.

Related

Email is not Delivering using Sendgrid SMTP

I am using CI library to send an email using Sendgrid smtp.
but it is not giving any response, neither email is sending.
$this->load->library('email');
$config['protocol'] = 'smtp';
$config['smtp_host'] = 'smtp.sendgrid.net';
$config['smtp_user'] = 'api key name';
$config['smtp_pass'] = 'api key';
$config['smtp_port'] = '587';
$config['smtp_keepalive'] = 'TRUE';
$this->email->initialize($config);
$this->email->from('test#test.com', FROM_NAME);
$this->email->to($email);
extract($arr_var);
$sub=addslashes($row['subject']);
eval("\$subject= \"$sub\";");
$body=addslashes($row['message']);
eval("\$message= \"$body\";");
if ($subject!='') {
$this->email->subject(stripslashes($subject));
} else {
$this->email->subject($row['subject'].' - '.$this->config->item('app_title'));
}
$this->email->message($message);
$bool=$this->email->send();
Using above code i am sending en email CI v3 but it I am not receiving any email?
Twilio SendGrid developer evangelist here.
Two things stand out to me here.
First, where you set the smtp username, it should be the string "apikey" (see the instructions for sending with SMTP here).
Second, the from address you are sending from is "test#test.com". SendGrid requires you to verify the identity you send from. You either need go through Single Sender Verification or Domain Authentication and then use an email address that you have verified to send the emails from.
Once you have sorted those two bits out, your emails should send successfully.

How to send email notification when colab processing is complete

I have a Colab task for data processing.
I want to send a Gmail notification when this task is finished.
Can anyone help me?
You can use smtplib to send an email. For more details goto this link.
import smtplib
sender = 'from#fromdomain.com'
receivers = ['to#todomain.com']
message = """From: From Person <from#fromdomain.com>
To: To Person <to#todomain.com>
Subject: SMTP e-mail test
This is a test e-mail message.
"""
try:
smtpObj = smtplib.SMTP('mail.your-domain.com', 25)
smtpObj.sendmail(sender, receivers, message)
print "Successfully sent email"
except SMTPException:
print "Error: unable to send email"

Getting error while sending email by using Streamsets

i am trying to send an email by using StreamSets.
for this, i am using Directory as Source(list of receipts in the text file) and
Jython Evaluator for Processing and trash for Destination(for testing only).
when i run pipeline, running without any error. but getting error mail to my sender_email like this:
Your message wasn't delivered to com.streamsets.pipeline.stage.processor.scripting.ScriptRecord#3ea57368 because the domain 3ea57368 couldn't be found. Check for typos or unnecessary spaces and try again.
Here is my sample code:
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import logging
for record in records:
try:
msg = MIMEMultipart()
msg['Subject'] = 'simple email in python'
message = 'here is the email'
msg.attach(MIMEText(message))
mailserver = smtplib.SMTP('smtp.gmail.com',587)
mailserver.ehlo()
mailserver.starttls()
mailserver.ehlo()
mailserver.login('sateesh.karuturi9#gmail.com', 'password')
mailserver.sendmail('sateesh.karuturi9#gmail.com',record,msg.as_string())
output.write(record)
mailserver.quit()
except Exception as e:
error.write(record, str(e))
Here is my error:
You're seeing this because you're using the record object as the email address - com.streamsets.pipeline.stage.processor.scripting.ScriptRecord#3ea57368 is the string value of a record instance.
If you're using text data format in the Directory origin, then you can use record.value['text'] instead of record:
mailserver.sendmail('sateesh.karuturi9#gmail.com', record.value['text'], msg.as_string())
If you're using a different data format (delimited, JSON etc), use preview to figure out which field the email address is in, and reference it the same way.

Send email via MATLAB

I need to send an email via MATLAB and I've read the instructions for sendmail and lots of answers around here. I've tried 3 email providers and I can't really use any of them:
Gmail: I can only send email when I deactivate my anivirus
Hotmail and Yahoo: Error using sendmail (line 171) Exception reading response; Connection reset
Hotmail and Yahoo (antivirus off): Error using sendmail (line 171) Exception reading response; Unrecognized SSL message, plaintext connection?
Here's the code
mail = 'user#service.com';
password = 'passwordgoeshere';
setpref('Internet','SMTP_Server','smtp.server.com');
setpref('Internet','E_mail',mail);
setpref('Internet','SMTP_Username',mail);
setpref('Internet','SMTP_Password',password);
props = java.lang.System.getProperties;
props.setProperty('mail.smtp.auth','true');
props.setProperty('mail.smtp.socketFactory.class', 'javax.net.ssl.SSLSocketFactory');
props.setProperty('mail.smtp.socketFactory.port',port);
sendmail(mail,'Test from MATLAB','Hello! This is a test from MATLAB!')
I've used the following variables:
Gmail: smtp.gmail.com port=465
Hotmail: smtp.live.com port=465 and port=587
Yahoo: smtp.mail.yahoo.com port=587
Since deactivating the antivirus is not a good option, can anyone help me solving this?
Thank you
An alternative way on linux is to run a command line that send the email.
unix('echo "message" | mail -s "subject" example#gmail.com');
A similar method should be available for windows.
For Gmail
Change your settings to allow less secure apps to access your account. Go to the "Less secure apps" section in My Account.
Next to "Access for less secure apps," select Turn on. (Note to Google Apps users: This setting is hidden if your administrator has locked less secure app account access.)
In Matlab:
mail = 'user#otherdomain.com';
password = 'myPassword';
% Set up the preferences
setpref('Internet','E_mail',mail);
setpref('Internet','SMTP_Server','smtp.gmail.com');
setpref('Internet','SMTP_Username',mail);
setpref('Internet','SMTP_Password',password);
% The following is necessary only if you are using GMail as
% your SMTP server.
props = java.lang.System.getProperties;
props.setProperty('mail.smtp.auth','true');
props.setProperty('mail.smtp.socketFactory.class', 'javax.net.ssl.SSLSocketFactory');
props.setProperty('mail.smtp.socketFactory.port','465');
subject = 'Test subject';
message = 'Test message';
sendmail(mail,subject,message)
Simply declare
mail = 'user';
Drop the extension #service.com for the variable mail.

Using CakePHP's Email component

I try to send a simple Email via CakePHP's Email Component. I'm using following code from the cookbook documentation:
$this->Email->from = 'Irgendjemand <irgendjemand#example.com>';
$this->Email->to = 'Irgendjemand Anderes <irgendjemand.anderes#example.com>';
$this->Email->subject = 'Test';
$this->Email->send('Dies ist der Nachrichtenrumpf!');
The send()-method does only return a boolean value with the value false - but no error or warning occurs.
Does somebody have a solution for that?
Have you tried changing the delivery options? There are three options: mail, smtp and debug.
$this->Email->delivery = 'debug';
$this->Email->send('test message');
debug($this->Session->read('Message.email'));
You can debug with EMail. Set the delivery to debug and the email message will be set to Session.message:
if (Configure::read('debug') > 1) {
$this->Email->delivery = 'debug';
}
$ret = $this->Email->send();
if (Configure::read('debug') > 1) {
pr($this->Session->read('Message.email'));
}
Which OS are you on? If Windows, this note may be of interest:
Note: The Windows implementation of mail() differs in many ways from the Unix implementation.
...
As such, the to parameter should not be an address in the form of
"Something <someone#example.com>". The mail command may not parse this properly while talking with the MTA.
Secondly, it may just be the case that no mail server will accept outgoing mail from your local machine due to spam protection. I have often seen that the same mail() function will not work locally, but works fine once uploaded to a trustworthy server. You could try to use an authenticated mail relay in that case (SMTP).