--I want to send an email with python
I wanted to be notified by email of the results of various processes, so I incorporated email sending with Outlook
.
Since it is a daily operation, if I set it in the task scheduler, it means that an email was sent, but it is not actually sent.
It will be sent if you execute it directly, not from the task scheduler.
After some research, I found it a bit difficult to use office
products such as Outlook
in a server environment.
I found that I could use the standard library as an alternative, so make a note of it.
--Use the standard libraries `smtplib``` and ```email``` --In addition,
server host name
,
port number
,
authentication ID
,
authentication password
is required --However, it may be OK without ``` authentication ID`
and authentication password` `` (depending on the environment) --If there are multiple destinations, they will be sent one by one, so pass the `` `destination address
in a list and turn it with the `` `for``` statement.
sample.py
from email import message
import smtplib
smtp_host = 'hostname'
smtp_port =Host number
smtp_account_id = 'Authentication ID'
smtp_account_pass = 'Authentication password'
send_from = '[email protected]'
l_send_to = [
'[email protected]',
'[email protected]'
]
subject = 'Work report'
content = f'Work is finished'
for s in l_send_to:
msg = message.EmailMessage()
msg.set_content(content)
msg['Subject'] = subject
msg['From'] = send_from
msg['To'] = s
server = smtplib.SMTP(smtp_host, smtp_port, timeout=10)
server.login(smtp_account_id, smtp_account_pass) #Sometimes it ’s okay without it
server.send_message(msg)
server.quit()
Recommended Posts