ChatGPT - 파이썬 이메일발송
파이썬 이메일전송
ChatGPT를 활용하여 파이썬으로 이메일전송 프로그램을 만들려고 한다.
[질문]
파이썬으로 이메일 보내기 위한 샘플 코드를 만들어주세요.
[답변]
Sure, here's a sample code for sending an email using Python. You will need to have a valid email account and SMTP server details to use this code.
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
sender_email = "sender_email@example.com"
receiver_email = "receiver_email@example.com"
password = "your_email_password"
message = MIMEMultipart("alternative")
message["Subject"] = "Sample email from Python"
message["From"] = sender_email
message["To"] = receiver_email
# You can customize the content of the email here.
text = "Hi, this is a sample email sent using Python."
html = """\
<html>
<body>
<p>Hi,<br>
This is a sample email sent using <b>Python</b>.
</p>
</body>
</html>
"""
part1 = MIMEText(text, "plain")
part2 = MIMEText(html, "html")
message.attach(part1)
message.attach(part2)
# Connect to SMTP server and send email.
with smtplib.SMTP("smtp.gmail.com", 587) as server:
server.starttls()
server.login(sender_email, password)
server.sendmail(sender_email, receiver_email, message.as_string())
위 소스를 붙여 넣어 실행해 보았다.
아래 메일 정보는 적절하게 수정해야 한다.
적고 보니 메일서버를 모를 수 있다고 생각했다? 다음 시간엔 간단하게 구글 SMTP 서버를 연동하는 법에 대해서 소개해야겠다.
그랬더니 위처럼 에러 뿜뿜
우선, SMTP를 사용하기 위해 필요한 smtplib 모듈을 import 한다.
그 아래에 클래스들을 보면 MIME이라는 이름을 가지고 있는데,
MIME는 이메일과 함께 전송할 파일을 텍스트 형식으로 변환해 준다.
pip install smtplib
pip install email
위 넣었는데 pip upgrade를 하라고 나오면 아래
pip install --upgrade pip
어 그래도 이상한 에러가 난다.
[질문]
아래와 같은 오류가 있는데, 무엇인지 아시나요?
파일 "d:\filename\email.py", 줄 1, <filename>
가져오기 smtplib
파일 "C:\프로그램 파일\Windows 앱\Python Software Foundation.Python.3.10_3.10.2800.0_x64__qbz5n2kfra8p0\lib\smtplib.py", 줄 47, <http>
e-메일.vmdk 가져오기
파일 "d:\filename\email.py", 줄 2, <filename>
from email.mime.text MIMetext 가져오기
ModuleNotFoundError: '이메일'이라는 이름의 모듈이 없습니다.mime'; 'email'은 패키지가 아닙니다.
[답변]
It looks like the error is being caused because you have named your script email.py, and it is conflicting with the built-in email module in Python.
When you try to import smtplib in your script, it is importing the built-in email module as well, but since your script is named email.py, it is trying to import from your own script instead of the built-in module, which is causing the error.
To fix this error, you should rename your script to something else, such as send_email.py, so that it does not conflict with the built-in modules in Python. After renaming the file, try running the script again, and the error should be resolved.
[번역]
스크립트 이름을 email.py으로 지정하여 Python의 기본 제공 이메일 모듈과 충돌하여 오류가 발생한 것 같습니다.
스크립트에서 smtplib를 가져오려고 하면 기본 제공 e-메일 모듈도 가져오지만 스크립트 이름이 email.py이므로 기본 제공 모듈 대신 사용자 스크립트에서 가져오려고 하므로 오류가 발생합니다.
이 오류를 수정하려면 스크립트 이름을 send_email.py와 같은 다른 이름으로 변경하여 Python의 내장 모듈과 충돌하지 않도록 해야 합니다. 파일 이름을 변경한 후 스크립트를 다시 실행하면 오류가 해결됩니다.
[의견]
미쳤다.. 파이썬 파일 만들 때 email.py이라고 만들어서 기존 이메일 모듈과 충돌하여 발생한 오류란다.
그럼 파일명을 수정한 후 다시 실행
짜잔 아래와 같이 아웃룩 메일로 메일을 정상적으로 수신하였다.
오늘도 보람찬 생존 ^.^