skip to Main Content

so i managed to send emails via EmailJS but how can i add an attachment?

i created a pdf like this:

Uint8List pdfInBytes = await pdf.save();
  final blob = html.Blob([pdfInBytes], 'application/pdf');
  final url = html.Url.createObjectUrlFromBlob(blob);
  anchor = html.document.createElement('a') as html.AnchorElement
    ..href = url
    ..style.display = 'none'
    ..download = 'pdf_' + timestamp.toString() + '.pdf';
  html.document.body!.children.add(anchor);

so i have the pdf as a blob file (opening it via blob url works) but how can i attach it to the mail?

thanks!

i tried this:

  final response = await http.post(url,
      headers: {'Content-Type': 'application/json'},
      body: json.encode({
        'service_id': serviceId,
        'template_id': templateId,
        'user_id': userId,
        'attachments': {'test.pdf': blob},
        'template_params': {
          'user_name': name,
          'user_email': email,          
          'user_message': message,
        }
      }));

this gives me the following exception:

Error: Converting object to an encodable object failed: Instance of '_Future<Blob>'

2

Answers


  1. Chosen as BEST ANSWER

    update!

    converting the file works now like this:

    final reader = html.FileReader()..readAsDataUrl(blob); //=> read data
    await reader.onLoadEnd.firstWhere((element) => element.isTrusted ?? false);
        
    var webBytes = UriData.parse(reader.result.toString()).contentAsBytes();
        
    String base64bytes = base64Encode(webBytes);
    

    new problem:

    when sending the mail i get http status code 400 (wrong userId / userId missing) although the userId is correct. (it works without attachments)

    any ideas?!


  2. This is a synchronization issue.
    The Future takes time to read your data, and your program isn’t waiting for it to finish. The correct implementation is to only execute the HTTP POST after the Future loads the PDF.

    void runMyFuture() {
        readPDFBlob().then((blob) {
            // Run the code here using the value
            // http.post( ... )
        });
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search