Cours React Native · Module 13: API natives

expo-sms & expo-mail-composer - SMS et Email

2 min de lecture ·
Dans cette leçon3

Envoie des SMS et des emails !

expo-sms

npx expo install expo-sms
import * as SMS from 'expo-sms';

async function sendSMS(phoneNumber: string, message: string) {
  const isAvailable = await SMS.isAvailableAsync();

  if (!isAvailable) {
    Alert.alert('SMS non disponible');
    return;
  }

  const { result } = await SMS.sendSMSAsync(
    [phoneNumber], // On peut fournir plusieurs numéros
    message
  );

  // result : 'sent', 'cancelled' ou 'unknown'
  return result;
}

// Exemple d'utilisation
await sendSMS('+48123456789', 'Salutations d\'Atlantis !');

expo-mail-composer

npx expo install expo-mail-composer
import * as MailComposer from 'expo-mail-composer';

async function sendEmail() {
  const isAvailable = await MailComposer.isAvailableAsync();

  if (!isAvailable) {
    Alert.alert('Email non disponible');
    return;
  }

  const result = await MailComposer.composeAsync({
    recipients: ['contact@atlantis.app'],
    ccRecipients: ['copy@atlantis.app'],
    bccRecipients: ['hidden@atlantis.app'],
    subject: 'Message d\'Atlantis',
    body: 'Bonjour ! Voici un message envoyé depuis l\'application Atlantis.',
    isHtml: false,
    attachments: ['/path/to/file.pdf'], // Pièces jointes optionnelles
  });

  // result.status : 'sent', 'saved', 'cancelled', 'undetermined'
  return result;
}

Service de communication

const CommunicationService = {
  async sendSMS(phone: string, message: string) {
    if (await SMS.isAvailableAsync()) {
      return SMS.sendSMSAsync([phone], message);
    }
    throw new Error('SMS non disponible');
  },

  async sendEmail(to: string, subject: string, body: string) {
    if (await MailComposer.isAvailableAsync()) {
      return MailComposer.composeAsync({
        recipients: [to],
        subject,
        body,
      });
    }
    throw new Error('Email non disponible');
  },

  async call(phone: string) {
    const url = `tel:${phone}`;
    if (await Linking.canOpenURL(url)) {
      await Linking.openURL(url);
    }
  },
};
Code de cette leçon : App.tsx
import React from 'react';
import { View, Text, Button, StyleSheet, Alert } from 'react-native';
import * as SMS from 'expo-sms';
import * as MailComposer from 'expo-mail-composer';
import * as Linking from 'expo-linking';

// Service de communication utilisant les fonctionnalités natives du téléphone
const CommunicationService = {
  async sendSMS(phone: string, message: string) {
    // TODO : vérifier la disponibilité : if (await SMS.isAvailableAsync()) { ... }
    // TODO : à l'intérieur, envoyer le SMS : return SMS.sendSMSAsync([phone], message);
    // TODO : sinon : throw new Error('SMS unavailable');
  },

  async sendEmail(to: string, subject: string, body: string) {
    // TODO : vérifier la disponibilité : if (await MailComposer.isAvailableAsync()) { ... }
    // TODO : à l'intérieur, envoyer l'e-mail :
    //   return MailComposer.composeAsync({ recipients: [to], subject, body });
    // TODO : sinon : throw new Error('Email unavailable');
  },

  async call(phone: string) {
    const url = `tel:${phone}`;
    // TODO : vérifier si l'URL peut être ouverte : if (await Linking.canOpenURL(url)) { ... }
    // TODO : à l'intérieur, l'ouvrir : await Linking.openURL(url);
  },
};

export default function App() {
  return (
    <View style={styles.screen}>
      <Text style={styles.title}>Communication de l'Atlantide</Text>
      <Button
        title="Envoyer un SMS"
        onPress={() => CommunicationService.sendSMS('+48123456789', 'Bonjour depuis Atlantide !')}
      />
      <Button
        title="Envoyer un e-mail"
        onPress={() => CommunicationService.sendEmail('contact@atlantyda.app', 'Salut', 'Contenu')}
      />
      <Button
        title="Appeler"
        onPress={() => CommunicationService.call('+48123456789')}
      />
    </View>
  );
}

const styles = StyleSheet.create({
  screen: {
    flex: 1,
    justifyContent: 'center',
    padding: 24,
    gap: 12,
    backgroundColor: '#1a5276',
  },
  title: {
    fontSize: 22,
    color: '#fff',
    fontWeight: '600',
    marginBottom: 16,
  },
});

Entrées de la documentation utilisées dans cette leçon

Tu as repéré une erreur dans cette leçon ?

Teste tes connaissances

Réponds aux questions de cette leçon. Choisis une réponse pour voir tout de suite si elle est correcte.

  1. 1. Comment envoie-t-on un SMS ?

  2. 2. Comment vérifie-t-on la disponibilité des SMS ?

Tâches pratiques dans le jeu

  • Clique dans l'ordre

    Clique sur les éléments pour envoyer un email :

  • Éditeur de code

    Complète le code de CommunicationService.

  1. QuestionSMS.sendSMSAsync
  2. Clique dans l'ordreMailComposer.composeAsync
  3. QuestionisAvailableAsync
  4. Exercice de codeService de communication
  5. Projet à envoyerProjet : Intégration native
  6. VidéoRésumé du module

Articles utiles