如何启动和打开React Native的电子邮件客户端?

131

我不想撰写电子邮件,我只想在react-native应用程序中能够启动用户设备(iOS和Android)上的主要电子邮件应用程序。

场景:我将在注册时向用户发送验证电子邮件。


我们遇到了同样的问题。 这个答案展示了如何在安卓上打开"邮件客户端选择器",我们需要类似于iOS的东西。 - miah
这在使用 Gmail 客户端的新 Android 手机上不起作用。它仅适用于使用电子邮件客户端的旧 Android 手机。 - johnrubythecat
15个回答

225

React Native 打开邮件功能

<Button onPress={() => Linking.openURL('mailto:support@example.com') }
      title="support@example.com" />

使用主题和正文打开React Native邮件功能

<Button onPress={() => Linking.openURL('mailto:support@example.com?subject=SendMail&body=Description') }
      title="support@example.com" />

React Native打开URL

<Button onPress={() => Linking.openURL('https://www.google.co.in/') }
      title="www.google.co.in" />

##别忘了导入

import { Linking } from 'react-native'

注意:在iOS模拟器中不受支持,因此您必须在设备上进行测试。


30
openURL('mailto:...') 打开的是一封新邮件的编辑页面,而不是已有的邮件客户端。Jasan明确表示不希望这样做。请注意保留原意并使文本易于理解。 - miah
40
注意:iOS模拟器不支持此功能,因此您必须在设备上进行测试。 - Ben Butterworth
@Vishal Vaghasiya 在这封电子邮件中,如果我传递了带有更多内容的主体! 那么内容会被截断。 需要您的关注。 - Zala Janaksinh
请注意,如果主题包含电子邮件,则无法正常工作,您需要使用URL编码解码主题和正文。const subject = encodeURI(strings.feedbackSubject); - Simon K. Gerges
提示:如果你想在主题或正文中使用空格,你需要用encodeURIComponent将你的消息包裹起来,将空格替换为%20 例如:mailto:somethingemail@gmail.com?subject=${encodeURIComponent("This is a subject")} https://github.com/facebook/react-native/issues/36680#issuecomment-1488093034 - undefined

62

很不幸,之后的回答都不正确

我不想写一封电子邮件。我只想能够启动主要的电子邮件应用程序

我希望有相同的行为:

  1. 登录屏幕,有一个名为打开电子邮件应用的按钮
  2. 用户打开他的电子邮件应用程序
  3. 他可以点击神奇链接以返回应用程序

跟Slack Onboarding中的魔法链接差不多

enter image description here

我发现了一个使用库react-native-email-link的解决方案。 您可以从React Native中打开电子邮件客户端(用于“魔术链接”功能)。

  • 适用于Android。
  • 如果您要在iOS上尝试,则需要实际设备,因为在iOS模拟器上没有mail.app

4
这个回答比帖子中其他所有内容都更正确。在iOS上一个简单的解决方案是调用 Linking.openURL('message://'),它会打开 Mail.app。上述提到的库可以处理跨移动操作系统的多个邮件应用程序。 - filipe
1
我有所怀疑,这就是为什么我提到了iOS,并且仍然认为你建议的库是更好的选择 :) - filipe
我认为可以不使用库来解决这个问题。 - lodey

12

18
但我不想发送邮件,我只想打开邮件应用程序,让用户阅读消息。特别是我刚发送的验证电子邮件。 - jasan
1
你是否曾经找到过在RN中仅打开电子邮件应用程序而不是撰写新电子邮件的解决方案? - mindbomb
1
这对我来说是有效的,尽管第一个&应该是一个? - mvandillen
7
请注意,在模拟器中会出现错误,因为邮件应用程序未安装。 - Michael Falck Wedelgård

11

Expo.io 纯 JS/TypeScript 解决方案:

import * as IntentLauncher from 'expo-intent-launcher';

// ...

  public openMailClientIOS() {
    Linking.canOpenURL('message:0')
      .then(supported => {
        if (!supported) {
          console.log('Cant handle url')
        } else {
          return Linking.openURL('message:0')
            .catch(this.handleOpenMailClientErrors)
        }
      })
      .catch(this.handleOpenMailClientErrors)
  }

  public openMailClientAndroid() {

    const activityAction = 'android.intent.action.MAIN'; // Intent.ACTION_MAIN
    const intentParams: IntentLauncher.IntentLauncherParams = {
      flags: 268435456, // Intent.FLAG_ACTIVITY_NEW_TASK
      category: 'android.intent.category.APP_EMAIL' // Intent.CATEGORY_APP_EMAIL
    };

    IntentLauncher.startActivityAsync(activityAction, intentParams)
      .catch(this.handleOpenMailClientErrors);
  }

iOS邮件中可以正常工作,Android中也可以。

Android Intent文档: https://developer.android.com/reference/android/content/Intent#ACTION_MAIN

Expo IntentLauncher文档: https://docs.expo.io/versions/latest/sdk/intent-launcher/


Android版本需要通过安装expo-intent-launcher更改本地代码。 - RayKay91

6

在iOS上打开电子邮件应用程序:

 Linking.canOpenURL('message:')
    .then(supported => {
        if (!supported) {
          console.log('Cant handle url')
        } else {
          return Linking.openURL('message:')
        }
      })
      .catch(err => {
        console.error('An error occurred', err)
      })

2

您可以使用此方法打开任何电子邮件客户端,并发送带有某些数据的电子邮件。

export const sendEmailViaEmailApp = (toMailId, subject, body) => {
  if (!isUndefined(toMailId)) {
    let link = `mailto:${toMailId}`;
  if (!isUndefined(subject)) {
    link = `${link}?subject=${subject}`;
  }
 if (isUndefined(subject)) {
   link = `${link}?body=${body}`;
 } else {
   link = `${link}&body=${body}`;
 }

Linking.canOpenURL(link)
  .then(supported => {
    if (supported) {
      // 'mailto:support@example.com?subject=Billing Query&body=Description'
      Linking.openURL(link);
    }
  })
  .catch(err => console.error('An error occurred', err));
} else {
  console.log('sendEmailViaEmailApp -----> ', 'mail link is undefined');
 }
};

将此方法放入工具类中,并在任何您想要使用的地方使用此方法。


1
import { View,Linking,Text, Image,TouchableOpacity } from 'react-native';

const emailId= 'care@flipkart.com'

 const onPressEmailClick = (email) => {
        Linking.openURL('mailto:'+email)
      //  Linking.openURL('mailto:Care@amazon.com')
     } 

  <View style={{ flexDirection: "row", alignItems: "center", justifyContent: "center" }} >

  <Text style={{ textAlign: "center", marginTop: 15, color: "black" }} >
           {"For any query mail us "}
  </Text>

    <TouchableOpacity
      onPress={() => onPressEmailClick(emailId)} >
      <Text style={{ textAlign: "center", marginTop: 15, color: "black", textDecorationLine: 'underline' }} >
           {emailId}
       </Text>
   </TouchableOpacity>

0
您可以使用此URL googlegmail:// 打开Gmail应用程序,这是Gmail的方案。第一次打开Gmail时,它会弹出一个警告,显示“想要打开Gmail”,用户可以点击确定或取消。这种行为只会发生一次。
这不会打开电子邮件撰写器,而是直接进入用户的主收件箱。

0

我找到了一种方法来打开邮件账户,而不是撰写邮件。由于需要物理iOS设备,我只在安卓(三星S9 +)上进行了测试,并且它有效。

import { openInbox } from "react-native-email-link";
import * as IntentLauncher from 'expo-intent-launcher';

const openMail = async () => {
  if (Platform.OS === "ios") {
    try {
      await openInbox({ title: "Open mail app" });
    } catch (error) {
      console.error(`OpenEmailbox > iOS Error > ${error}`);
    }
  }

  if (Platform.OS === "android") {
    const activityAction = "android.intent.action.MAIN";
    const intentParams = {
      category: "android.intent.category.APP_EMAIL",
    };
    IntentLauncher.startActivityAsync(activityAction, intentParams);
  }
}

-1
import { Linking } from 'react-native'

React Native Open Mail 

<TouchableOpacity onPress={() => Linking.openURL('mailto:support@example.com')}>
   <Text>support@example.com</Text>
</TouchableOpacity>


React Native Open Mail With Subject & Body 

<TouchableOpacity onPress={() => Linking.openURL('mailto:support@example.com?subject=sendmail&body=details')}>
   <Text>support@example.com</Text>
</TouchableOpacity>

this will only work in real device. not working in iOS simulator.


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接