[Tutorial] Send Email with Cocos2d-x 3.0

I’m currently using 3.4, so this is untested on newer releases.

In these folders and files make the following changes:

(Your game)->cocos2d/cocos/platforms/CCApplicationProtocol.h:
Add this line under openURL:

virtual bool sendEmail(const std::string &email) = 0;

For iOS
Untested, but should work. Note that this probably won’t work on a simulator.

(Your game)->cocos2d/cocos/platforms/ios/CCApplication-ios.h:
Add this line under openURL:

virtual bool sendEmail(const std::string &email);

(Your game)->cocos2d/cocos/platforms/ios/CCApplication-ios.mm:
Add these lines under openURL method:

bool Application::sendEmail(const std::string &email) {
    NSString *convertedString = [NSString stringWithUTF8String:email.c_str()];
NSString *emailString = [NSString stringWithFormat:@"mailto:%@", convertedString];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:emailString]];
return YES;
}

Android:
Tested. Search for filenames under your project to get the path.

In CCApplication-android.h:
Under openUrl add:

virtual bool sendEmail(const std::string &email);

In CCApplication-android.cpp:
Under openUrl method add:

bool Application::sendEmail(const std::string &email)
{
    return sendEmailJNI(email.c_str());
}

Cocos2dxHelper.java:
Under openURL method add:

public static boolean sendEmail(String email) { 
    boolean ret = false;
    try {
        Intent i = new Intent(Intent.ACTION_SEND);
        i.setType("message/rfc822");
        i.putExtra(Intent.EXTRA_EMAIL, email);
        i.putExtra(Intent.EXTRA_SUBJECT, "Your Subject"); // remove if none
        sActivity.startActivity(Intent.createChooser(i, "Select application"));
        ret = true;
    } catch (Exception e) {
    }
    return ret;
}

In Java_org_cocos2dx_lib_Cocos2dxHelper.h:
Under openURLJNI add:

extern bool sendEmailJNI(const char* email);

In Java_org_cocos2dx_lib_Cocos2dxHelper.cpp:
Under openURLJNI add:

extern bool sendEmailJNI(const char* email) {
JniMethodInfo t;

bool ret = false;
if (JniHelper::getStaticMethodInfo(t, CLASS_NAME, "sendEmail", "(Ljava/lang/String;)Z")) {
    jstring stringArg = t.env->NewStringUTF(email);
    ret = t.env->CallStaticBooleanMethod(t.classID, t.methodID, stringArg);
    
    t.env->DeleteLocalRef(t.classID);
    t.env->DeleteLocalRef(stringArg);
}
return ret;
}

Please like if this post helped you.

Help credit to http://www.smarts3.in/articles/cocos2dx/send-mail-in-cocos2dx-android/37

2 Likes