'How to send direct email by Flutter web

I Am Building a flutter web i have to send form Data by email to my Gmail email address How Can i. Please Help Me. I had User "mailer 3.0.4" and flutter_email_sender: ^2.2.2 But They Both are not working... Here Is My Code:

  // Perform login or signup
  Future<void> _validateAndSubmitForInformationForm() async {
    print('1');
    final MailOptions mailOptions = MailOptions(
      body: 'a long body for the email <br> with a subset of HTML',
      subject: 'the Email Subject',
      recipients: ['[email protected]'],
      isHTML: true,
      bccRecipients: ['[email protected]'],
      ccRecipients: ['[email protected]'],
//      attachments: [
//        'path/to/image.png',
//      ],
    );
    print('3');

    await FlutterMailer.send(mailOptions);
    print('2');
  }


Solution 1:[1]

You can use something like SendGrid to send an e-mail from flutter mobile with something like this: sorry for the bad formatting.

import 'package:http/http.dart' as http;

class SendGridUtil {
  static sendRegistrationNotification(String email) async {
    Map<String, String> headers = new Map();
    headers["Authorization"] =
        "Bearer $$$SENDGRIDAPIKEY$$$";
    headers["Content-Type"] = "application/json";

    var url = 'https://api.sendgrid.com/v3/mail/send';
    var response = await http.post(url,
        headers: headers,
        body:
            "{\n          \"personalizations\": [\n            {\n              \"to\": [\n                {\n                  \"email\": \"[email protected]\"\n                },\n                {\n                  \"email\": \"[email protected]\"\n                }\n              ]\n            }\n          ],\n          \"from\": {\n            \"email\": \"[email protected]\"\n          },\n          \"subject\": \"New user registration\",\n          \"content\": [\n            {\n              \"type\": \"text\/plain\",\n              \"value\": \"New user register: $email\"\n            }\n          ]\n        }");
    print('Response status: ${response.statusCode}');
    print('Response body: ${response.body}');
  }
}

To send an e-mail from flutter web you can use something like a firebase cloud function - this is a function that is executed when a new user is created in firebase auth:

import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';
const sgMail = require('@sendgrid/mail')

admin.initializeApp(functions.config().firebase);

exports.sendWelcomeEmail = functions.auth.user().onCreate(user => {

console.log("User with email created: " + user.email);

sgMail.setApiKey("$$$SENDGRIDKEY$$$");
const liftAiMsg = {
  to: '[email protected]',
  from: '[email protected]',
  subject: 'New user created',
  text: 'New user created with email: ' +user.email,
  html: "<strong>New user created with email:  "+user.email+"</strong>",
};

sgMail.send(liftAiMsg);

const customerMsg = {
  to: user.email,
  from: '[email protected]',
  subject: 'Welcome to LiftAI',
  text: 'Welcome to LiftAI',
  html: '<strong>Welcome to LiftAI!</strong>',
};

sgMail.send(customerMsg);


});

Solution 2:[2]

EDIT: This won't work because SendGrid (and MailJet) was designed to work only on servers and not on clients.

As @dazza500 said, you need to:

1) Register at https://app.sendgrid.com/
2) Create an API key
3) Optional: check documentation (https://sendgrid.com/docs/API_Reference/Web_API_v3/index.html)
4) And use this code (replacing SENDGRIDAPIKEY with your API key):

import 'package:http/http.dart' as http;

class SendGridUtil {
  static sendRegistrationNotification(String email) async {
    Map<String, String> headers = new Map();
    headers["Authorization"] =
        "Bearer SENDGRIDAPIKEY";
    headers["Content-Type"] = "application/json";

    var url = 'https://api.sendgrid.com/v3/mail/send';
    var response = await http.post(url,
        headers: headers,
        body:
            "{\n          \"personalizations\": [\n            {\n              \"to\": [\n                {\n                  \"email\": \"[email protected]\"\n                },\n                {\n                  \"email\": \"[email protected]\"\n                }\n              ]\n            }\n          ],\n          \"from\": {\n            \"email\": \"[email protected]\"\n          },\n          \"subject\": \"New user registration\",\n          \"content\": [\n            {\n              \"type\": \"text\/plain\",\n              \"value\": \"New user register: $email\"\n            }\n          ]\n        }");
    print('Response status: ${response.statusCode}');
    print('Response body: ${response.body}');
  }
}

Solution 3:[3]

You can create a specific (secured with a token for eg) WebAPI in your flavour language, and then make a simple POST call to it with the appropriate parameters.

In Flutter :

Future sendEmail(elementType elementoSent) async {
    var body = "Blabla, " + elementoSent.prpoerties;

    try {
        await http.post(
            "https://yourapiUrl.net/api/method",
            headers: {
                'Content-type': 'application/json',
                'Accept': 'application/json'
            },
            body: jsonEncode({"emailbody": '$body'}));
    } catch (e) {
        print(e);
    }
}

Here is an Web API code bloc for e.g. (in C#):

// POST api/<EmailsController>
[HttpPost]
public void Post([FromBody] EmailsModel model)
{
    if (model.Typemail == "1")
        _emailSender.SendEmailtoUserAsync("[email protected]", "mail object", model.EmailBody);
}

The _emailSender.SendEmailtoUserAsync uses an specific or an external mail service like MailJet or SendGrid.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 dazza5000
Solution 2
Solution 3 Matt Ke