Skip to content

Instantly share code, notes, and snippets.

@ssghost
Last active March 2, 2024 07:44
Show Gist options
  • Save ssghost/2885351659bb90f5aaab30a1c9f77290 to your computer and use it in GitHub Desktop.
Save ssghost/2885351659bb90f5aaab30a1c9f77290 to your computer and use it in GitHub Desktop.
use pyo3::prelude::*;
#[pyclass]
#[derive(Debug, Clone, PartialEq)]
enum AttachmentType {
Image,
Video,
Audio,
File,
}
#[pyclass(module = "pyo3_rust", get_all, set_all)]
#[derive(Debug, Clone, PartialEq)]
struct Attachment {
path: String,
attachment_type: AttachmentType,
}
#[pymethods]
impl Attachment {
#[new]
fn new(path: String, attachment_type: AttachmentType) -> Self {
Attachment {
path,
attachment_type,
}
}
fn __str__(&self) -> PyResult<String> {
Ok(format!("Attachment(path={}, attachment_type={:?})", self.path, self.attachment_type))
}
}
#[pyclass(module = "pyo3_rust", get_all, set_all)]
#[derive(Debug, Clone)]
struct Email {
subject: String,
body: String,
attachments: Vec<Attachment>,
}
#[pymethods]
impl Email {
#[new]
fn new(subject: String, body: String, attachments: Vec<Attachment>) -> Self {
Email {
subject,
body,
attachments,
}
}
fn __str__(&self) -> PyResult<String> {
Ok(format!("Email(subject={}, body={}, attachments={:?})", self.subject, self.body, self.attachments))
}
fn send(&mut self, to: String) -> PyResult<()> {
println!("Sending email to: {}", to);
println!("Subject: {}", self.subject);
println!("Body: {}", self.body);
for attachment in &self.attachments {
println!("Attachment: {:?}", attachment);
}
Ok(())
}
}
#[pymodule]
fn pyo3_email(_py: Python, m: &PyModule) -> PyResult<()> {
m.add_class::<Attachment>()?;
m.add_class::<Email>()?;
m.add_class::<AttachmentType>()?;
Ok(())
}
/*
import rustimport.import_hook
from pyo3_email import Attachment, AttachmentType, Email
def main():
attachment = Attachment("attachment.txt", AttachmentType.File)
print(attachment)
email = Email("This is the subject", "This is the body", [attachment])
print(email)
email.send("Example@ArjanCodes.com")
if __name__ == "__main__":
main()
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment