1import * as MailComposer from 'expo-mail-composer';
2import React from 'react';
3import { Alert, StyleSheet, Text, View } from 'react-native';
4
5import Button from '../components/Button';
6import MonoText from '../components/MonoText';
7import { useResolvedValue } from '../utilities/useResolvedValue';
8
9export default function MailComposerScreen() {
10  const [isAvailable, error] = useResolvedValue(MailComposer.isAvailableAsync);
11
12  const warning = React.useMemo(() => {
13    if (error) {
14      return `An unknown error occurred while checking the API availability: ${error.message}`;
15    } else if (isAvailable === null) {
16      return 'Checking availability...';
17    } else if (isAvailable === false) {
18      // On iOS device without Mail app installed it is possible to show mail composer,
19      // but it isn't possible to send that email either way.
20      return `It's not possible to send an email on this device. Make sure you have mail account configured and Mail app installed (iOS).`;
21    }
22    return null;
23  }, [error, isAvailable]);
24
25  if (warning) {
26    return (
27      <View style={{ justifyContent: 'center', alignItems: 'center', flex: 1 }}>
28        <Text>{warning}</Text>
29      </View>
30    );
31  }
32
33  return <MailComposerView />;
34}
35
36MailComposerScreen.navigationOptions = {
37  title: 'MailComposer',
38};
39
40function MailComposerView() {
41  const [status, setStatus] = React.useState<MailComposer.MailComposerStatus | null>(null);
42
43  const sendMailAsync = async () => {
44    try {
45      const { status } = await MailComposer.composeAsync({
46        subject: 'Wishes',
47        body: 'Dear Friend! <b>Happy</b> Birthday, enjoy your day! ��',
48        recipients: ['[email protected]'],
49        isHtml: true,
50      });
51      setStatus(status);
52    } catch (error) {
53      console.log('Error: ', error);
54      Alert.alert(`Something went wrong: ${error.message}`);
55    }
56  };
57
58  return (
59    <View style={styles.container}>
60      <Button onPress={sendMailAsync} title="Send birthday wishes" />
61      {status && <MonoText>Status: {status}</MonoText>}
62    </View>
63  );
64}
65
66const styles = StyleSheet.create({
67  container: {
68    flex: 1,
69    alignItems: 'center',
70    justifyContent: 'center',
71  },
72  capabilitiesContainer: {
73    alignItems: 'stretch',
74    paddingBottom: 20,
75  },
76});
77