-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmail_something.py
More file actions
289 lines (226 loc) · 10.1 KB
/
Copy pathmail_something.py
File metadata and controls
289 lines (226 loc) · 10.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
# SPDX-FileCopyrightText: © 2026 Michel Anders (varkenvarken) & contributors
#
# SPDX-License-Identifier: GPL-2.0-or-later
import re
from smtplib import SMTP_SSL, SMTPException
from email.message import EmailMessage
from typing import Literal
import bpy
from bpy.utils import register_class, unregister_class
from bpy_extras.io_utils import ImportHelper
from bpy.types import Context
# to prevent having to annotate the return type of every execute method with this rather unreadable chunk
EXECUTE_RETURN = set[
Literal["RUNNING_MODAL", "CANCELLED", "FINISHED", "PASS_THROUGH", "INTERFACE"]
]
bl_info = {
"name": "Mail example",
"author": "Michel Anders",
"version": (0, 0, 1),
"blender": (5, 0, 0),
"location": "User preferences",
"description": "Send a test mail",
"category": "Render",
}
# compile this only once so that the actual check can be quick
# note this email pattern might be overly restrictive,
# see: https://www.regular-expressions.info/email.html
valid_email_pattern = re.compile(
r"^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$", re.IGNORECASE
)
def is_valid_email_address(email: str) -> bool:
"""Check if the provided string is a valid email address.
Args:
email: The email address string to validate.
Returns:
True if the email matches the valid email pattern, False otherwise.
"""
return valid_email_pattern.match(email) is not None
def verify_smtp_connection() -> bool:
"""Test the SMTP connection with current addon preferences.
Attempts to establish an SMTP_SSL connection using the configured server,
port, sender email, and password. Updates the global connection_status
variable with the result.
Returns:
True if the connection and login were successful, False otherwise.
Also returns False if online access is blocked by user settings.
"""
global password
global connection_status
if bpy.app.online_access: # or bpy.app.online_access_override not needed, override indicates when overridden, that'all
assert bpy.context.preferences is not None # keep Pylance happy
prefs: RenderDonePreferences = bpy.context.preferences.addons[
__name__
].preferences # type: ignore
try:
with SMTP_SSL(host=prefs.server, port=prefs.port) as smtp:
smtp.login(user=prefs.sender, password=password) # type: ignore (if password is None login will fail which is perfectly ok)
smtp.noop()
connection_status = "Connection: ok"
return True
except Exception as e: # not just smtp exceptions also socket.gaierror
connection_status = f"Connection: error {str(e)}"
return False
else:
connection_status = "Connection: blocked by user (see prefs|system|network)"
return False
def send_smtp_message(content: str) -> bool:
"""Send an email message via SMTP.
Creates an email message with the provided content and sends it through
the configured SMTP server using credentials from addon preferences.
Updates the global connection_status variable with the result.
Args:
content: The body text of the email message to send.
Returns:
True if the message was sent successfully, False if sending failed.
"""
global password
global connection_status
assert bpy.context.preferences is not None # keep Pylance happy
prefs: RenderDonePreferences = bpy.context.preferences.addons[__name__].preferences # type: ignore
msg = EmailMessage()
msg.set_content(content)
msg["Subject"] = "Render job completed"
msg["From"] = prefs.sender
msg["To"] = prefs.email
try:
with SMTP_SSL(host=prefs.server, port=prefs.port) as smtp:
smtp.login(user=prefs.sender, password=password) # type: ignore (if password is None login will fail which is perfectly ok)
smtp.send_message(msg)
smtp.quit()
connection_status = "Connection: message sent"
return True
except (SMTPException, RuntimeError) as e:
connection_status = f"Connection: error {str(e)}"
return False
class SendTestmail(bpy.types.Operator):
bl_idname = "workspace.send_testmail"
bl_label = "Send a testmail"
def execute(self, context: Context) -> EXECUTE_RETURN:
if send_smtp_message("test email"):
self.report({"INFO"}, "SMTP server connection ok")
else:
self.report({"ERROR"}, "SMTP server connection failed")
return {"FINISHED"}
class VerifyServer(bpy.types.Operator):
bl_idname = "workspace.verify_server"
bl_label = "Verify SMTP server"
def execute(self, context: Context) -> EXECUTE_RETURN:
if verify_smtp_connection():
self.report({"INFO"}, "SMTP server connection ok")
else:
self.report({"ERROR"}, "SMTP server connection failed")
return {"FINISHED"}
connection_status = "Connection: unknown"
def reset_status(self, context):
"""
helper function to reset the connection_status variable.
"""
global connection_status
connection_status = "Connection: unknown"
password: str | None = None
def read_password():
"""Read password from file and update global password variable.
Reads the first line of the password file specified in addon preferences,
stores it in the global password variable, and sets a custom property in the window
manager to indicate whether the password was successfully loaded.
"""
global password
assert bpy.context.preferences is not None # keep Pylance happy
password = read_first_line(
bpy.context.preferences.addons[__name__].preferences.password_file # type: ignore (password_file is an attribute)
)
bpy.context.window_manager.password_loaded = password is not None # type: ignore (password_loaded is an attribute)
def read_first_line(filepath: str) -> str | None:
"""Read and return the first line from a file.
Args:
filepath: Path to the file to read.
Returns:
The first line of the file with leading/trailing whitespace stripped,
or None if the file cannot be read (e.g., missing or not readable).
"""
try: # can fail for several reasons: file might not exist, or is not readable, etc.
with open(filepath, "r", encoding="utf-8") as f:
return f.readline().strip()
except IOError:
return None
class ReadPasswordFromFile(bpy.types.Operator, ImportHelper): # type: ignore (check() method defined differently in each base class; not something we can fix)
"""
Lets the user select a file using the standard Blender file dialog
and sets the password to the first line of this file.
"""
bl_idname = "import.password"
bl_label = "Read password"
def execute(self, context: Context) -> EXECUTE_RETURN:
assert context.preferences is not None # keep Pylance happy
context.preferences.addons[__name__].preferences.password_file = self.filepath # type: ignore (password_file is an attribute as is filepath)
read_password()
return {"FINISHED"}
class RenderDonePreferences(bpy.types.AddonPreferences):
bl_idname = __name__ # important: this links these preferences with the current add-on; you still need to register the class though
email: bpy.props.StringProperty(
name="Recipient address",
description="Valid email address of the form someone@example.org",
) # type: ignore
sender: bpy.props.StringProperty(
name="Sender address",
description="Valid email address of the form someone@example.org",
update=reset_status,
) # type: ignore
server: bpy.props.StringProperty(
name="Email server",
description="Fully qualified name of the SMTP server",
default="smtp.example.com",
update=reset_status,
) # type: ignore
port: bpy.props.IntProperty(
name="Server port",
description="Port to use SMTP server (SSL is assumed)",
default=465,
min=1,
max=65535,
update=reset_status,
) # type: ignore
# don´t make these next two read only, otherwise we cannot even set them programmatically;
# make them read only in the draw method (or don´t even show them)
password_file: bpy.props.StringProperty(
name="Password file",
update=reset_status,
) # type: ignore
password_loaded: bpy.props.BoolProperty(name="Password loaded", default=False) # type: ignore
def draw(self, context):
global connection_status
# NOTE: unlike with operators there is no default draw implementation so if you don´t add it, you see nothing
layout = self.layout
recipient_row = layout.row()
address_row = layout.row()
password_row = layout.row()
server_row = layout.row()
recipient_row.alert = not is_valid_email_address(self.email)
recipient_row.prop(self, "email", text="Recipient")
address_row.alert = not is_valid_email_address(self.sender)
address_row.prop(self, "sender", text="Sender")
# the checkbox that indicates if the password was loaded is only set programmatically
# so here we show it disabled.
row2 = password_row.row()
row2.prop(context.window_manager, "password_loaded", text="Password")
row2.enabled = False
password_row.operator(ReadPasswordFromFile.bl_idname)
server_row.prop(self, "server", text="Server")
server_row.prop(self, "port", text="")
status_col = layout.column()
status_col.label(text=connection_status)
status_col.operator(VerifyServer.bl_idname)
status_col.operator(SendTestmail.bl_idname)
classes = (RenderDonePreferences, ReadPasswordFromFile, VerifyServer, SendTestmail)
def register():
for klass in classes:
register_class(klass)
bpy.types.WindowManager.password_loaded = bpy.props.BoolProperty( # type: ignore (we can define a new attribute dynamically no problem)
name="Password loaded", default=False
)
read_password()
verify_smtp_connection()
def unregister():
for klass in classes:
unregister_class(klass)