|
1 |
| -from django.core.mail import send_mail |
| 1 | +import smtplib |
| 2 | +from email.mime.multipart import MIMEMultipart |
| 3 | +from email.mime.text import MIMEText |
| 4 | + |
2 | 5 | from django.utils import dateformat, timezone
|
3 | 6 |
|
4 | 7 | from apps.core.models import CommunicationArticle, UserProfile
|
@@ -99,4 +102,51 @@ def send_email():
|
99 | 102 |
|
100 | 103 | mailing_list = _get_mailing_list()
|
101 | 104 |
|
102 |
| - send_mail( title, message, "[email protected]", mailing_list) |
| 105 | + smtp_send( title, message, "[email protected]", mailing_list, False) |
| 106 | + |
| 107 | + |
| 108 | +def smtp_send( |
| 109 | + title: str, |
| 110 | + message: str, |
| 111 | + sender_mail: str, |
| 112 | + mailing_list: list[str], |
| 113 | + each: bool = True, |
| 114 | +): |
| 115 | + """ |
| 116 | + Send email using SMTP relay gmail server. |
| 117 | +
|
| 118 | + each True: Send email to each receiver. Receivers cannot see other receivers. |
| 119 | + each False: Send email to all receivers. Receivers can see other receivers. |
| 120 | + """ |
| 121 | + allowed_mail_domain = ["@sparcs.org"] |
| 122 | + |
| 123 | + if not sender_mail.endswith(tuple(allowed_mail_domain)): |
| 124 | + raise ValueError("Invalid email domain") |
| 125 | + |
| 126 | + smtp = smtplib.SMTP("smtp-relay.gmail.com", 587) |
| 127 | + smtp.starttls() |
| 128 | + # smtp.login("", "") # TODO: Use ID, PW instead of IP Address Authentication |
| 129 | + smtp.ehlo() |
| 130 | + |
| 131 | + if each: |
| 132 | + for receiver in mailing_list: |
| 133 | + # print(f"[{mailing_list.index(receiver) + 1}/{len(mailing_list)}] Sending email to [{receiver}]") # FOR DEBUG |
| 134 | + msg = create_msg(title, sender_mail, message, receiver) |
| 135 | + smtp.sendmail(sender_mail, receiver, msg.as_string()) |
| 136 | + else: |
| 137 | + receivers = ", ".join(mailing_list) |
| 138 | + msg = create_msg(title, sender_mail, message, receivers) |
| 139 | + smtp.sendmail(sender_mail, mailing_list, msg.as_string()) |
| 140 | + |
| 141 | + smtp.quit() |
| 142 | + |
| 143 | + |
| 144 | +def create_msg( |
| 145 | + title: str, sender_mail: str, message: str, receiver_mail: str |
| 146 | +) -> MIMEMultipart: |
| 147 | + msg = MIMEMultipart() |
| 148 | + msg["Subject"] = title |
| 149 | + msg["From"] = sender_mail |
| 150 | + msg.attach(MIMEText(message, "plain")) # TODO: Use HTML instead of plain text |
| 151 | + msg["To"] = receiver_mail |
| 152 | + return msg |
0 commit comments