質問: smtplib.smtp('smtp.gmail.com:587') server.starttls() server.login(username,password) server.sendmail(fromaddr, toaddrs, msg) server.quit()
回答: def send_email(user, pwd, recipient, subject, body): import smtplib from = user to = recipient if isinstance(recipient, list) else [recipient] subject = subject text = body # prepare actual message message = """from: %s\nto: %s\nsubject: %s\n\n%s """ % (from, ", ".join(to), subject, text) try: server = smtplib.smtp("smtp.gmail.com", 587) server.ehlo() server.starttls() server.login(user, pwd) server.sendmail(from, to, message) server.close() print 'successfully sent the mail' except: print "failed to send mail" ポート465を使用したい場合はsmtp_sslオブジェクトを作成する必要があります。# smtp_ssl example server_ssl = smtplib.smtp_ssl("smtp.gmail.com", 465) server_ssl.ehlo() # optional, called by login() server_ssl.login(gmail_user, gmail_pwd) # ssl server doesn't support or need tls, so don't call server_ssl.starttls() server_ssl.sendmail(from, to, message) #server_ssl.quit() server_ssl.close() print 'successfully sent the mail'