Python's standard library has 'smtplib' module which defines an SMTP client session object that can be used to send mail via Python program.
A mail server is an application that handles and delivers e-mail over the internet. Outgoing mail servers implement SMTP, or Simple MailTransfer Protocol, servers which are an Internet standard for email transmission.
Incoming mail servers come in two main varieties. POP3, or Post office protocol and IMAP, or Internet Message Access Protocol.
This function returns an object of SMTP class. It encapsulates and manages a connection to an SMTP or ESMTP server. Following arguments are defined in the signature of this function −
|host||A string which is the name of the remote host to which to connect. |
|port||A number that specifies the port to which to connect. By default, smtplib.SMTP_PORT is used. |
|local_hostname||used as the FQDN of the local host in the HELO/EHLO command. |
|source_address|| a 2-tuple (host, port) object to which the socket to bind|
It has the following methods that support SMTP operations −
This method establishes a connection to a host on a given port.
This function takes username and password arguments to login to SMTP server.
This function terminates SMTP session.
The 'message' argument to this function is sent to server.
This function sends a command and returns its response code
This function identifies the server.
This function starts TLS mode.
This function receives reply from the server in the form of response code.
This function sends a command to the server.
This function converts the message to a byte string and passes it to send mail.
This command performs an entire mail transaction.
The arguments are −
|from_addr|| The address sending this mail.|
|to_addrs|| A list of addresses to send this mail to. |
|msg|| The message to send.|
Code below uses smtp server of gmail to send an email. The SMTP object uses gmail's smtp server at port 527. The ehlo() command identifies the server. We also activate Transport Layer Security to the outgoing mail message.
Next, the login() command is invoked by passing credentials as arguments toit. Finally the mail message is assembled by attaching it a header in the prescribed format and it is sent using sendmail() method. The SMTP object is closed afterward.
import smtplib content="HelloWorld" mail=smtplib.SMTP('smtp.gmail.com',587) mail.ehlo() mail.starttls() firstname.lastname@example.org' email@example.com' mail.login('firstname.lastname@example.org','m15v5l61') header='To:'+receipient+'\n'+'From:'\ +sender+'\n'+'subject:testmail\n' content=header+content mail.sendmail(sender,recipient, content) mail.close()
Before running above script, ensure that sender's gmail account is provided access to 'less secure apps'.
Set the shown toggle button to ON.
Execute above script after performing above setting. The message should be delivered to recipient's inbox.