sabuhish / fastapi-mail

Fastapi mail system sending mails(individual, bulk) attachments(individual, bulk)
https://sabuhish.github.io/fastapi-mail/
MIT License
698 stars 81 forks source link

Send local attachments #41

Closed UtopiaBe closed 3 years ago

UtopiaBe commented 3 years ago

Hello, How can i send files from local directory? when i give a "./app/files/file.pdf" path, I receive this error:

AttributeError: 'bytes' object has no attribute 'read'

or

attachments field type incorrect, must be UploadFile or path

Turall commented 3 years ago

Hi @UtopiaBe , Thank you for using fastapi-mail. Yes this a bug, and we fix it at in this PR. In the latest version it will be available. Pleasa update fastapi-mail to version 0.3.4.1

Turall commented 3 years ago

class EmailSchema(BaseModel):
    email: List[EmailStr]
    file: List[str]

conf = ConnectionConfig(
    MAIL_USERNAME = "YourUsername",
    MAIL_PASSWORD = "strong_password",
    MAIL_FROM = "your@email.com",
    MAIL_PORT = 587,
    MAIL_SERVER = "your mail server",
    MAIL_TLS = True,
    MAIL_SSL = False,
    USE_CREDENTIALS = True
)

app = FastAPI()

@app.post("/email")
async def simple_send(email: EmailSchema) -> JSONResponse:

    message = MessageSchema(
        subject="Fastapi-Mail module",
        recipients=email.email,  # List of recipients, as many as you can pass 
        body="simple file",
        attachments=email.file
        )

    fm = FastMail(conf)
    await fm.send_message(message)
    return JSONResponse(status_code=200, content={"message": "email has been sent"})

This is a simple example, maybe it will help you. 
The request body will look like

{
  "email": [
    "user@example.com"
  ],
  "file": ["/path/to/your/file.pdf"]
}

The file must be in the root of the project because we are checking file path in case path traversal
sabuhish commented 3 years ago

Thank you @Turall for the nice explanation and example you're provided! @UtopiaBe this should solve your problem.

UtopiaBe commented 3 years ago

Thank you @Turall and @sabuhish! Its workking :)

But when I attach a local file, the filename in attachment shows the path, not the filename only: mail

code:

pdf = "./app/pdf_agreements/destination.pdf"

message = MessageSchema(
    subject="test",
    recipients=[data.email],
    body="body",
    attachments=[pdf]
)
fm = FastMail(MAIL)
await fm.send_message(message)

return dict(detail="success")
sabuhish commented 3 years ago

Please check version 0.3.4.2.

sabuhish commented 3 years ago

@UtopiaBe does this release fixes your issue?

UtopiaBe commented 3 years ago

@sabuhish Yes it is! Great job guys! Keep it up :P