#-*- coding: utf-8 -*-
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import smtplib
import getpass
def send_mail(smtp_host, port, sender, receiver, username, password, tls_use = True):
# Create message object instance
msg = MIMEMultipart()
# Create message body
message = "Test mail from Python"
# Declare message elements
msg['From'] = sender
msg['To'] = receiver
msg['Subject'] = "Test mail subject"
# Add the message body to the object instance
msg.attach(MIMEText(message, 'plain'))
# Create the server connection
#server = smtplib.SMTP(smtp_host)
server = smtplib.SMTP(smtp_host, port)
# Switch the connection over to TLS encryption
# 서버 설정에 따라서 tls 를 지원하지 않을 수도 있음
if (tls_use):
server.starttls()
# Authenticate with the server
server.login(username, password)
# Send the message
server.sendmail(msg['From'], msg['To'], msg.as_string())
# Disconnect
server.quit()
print ("Successfully sent email message to %s" % (msg['To']))
def test_gmail(password):
smtp_host = "smtp.gmail.com"
port = "587"
sender = "anjinwoong12345@gmail.com"
receiver = "anjinwoong@naver.com"
username = "anjinwoong12345@gmail.com" ## login id
send_mail(smtp_host, port, sender, receiver, username, password, True)
if __name__=="__main__":
password = getpass.getpass()
try:
test_gmail(password)
except Exception as e:
print(e)
reference