Search code examples
sqliteangularionic2mailtongcordova

Angular2/Ionic2: Save Image from gallery and send as attachment via mailto


I am trying to save an image in my sqlite db and send it via the mailto service. Here is my code:

takepic() {
    var options = {
        quality: 80,
        destinationType: Camera.DestinationType.FILE_URI,
        sourceType: Camera.PictureSourceType.PHOTOLIBRARY,
        allowEdit: false,
        encodingType: Camera.EncodingType.JPEG,
        saveToPhotoAlbum: false
    };

    Camera.getPicture(options).then((data) => {
        var image = document.getElementById('myImage');
        image.src = imageURI;
        this.zone.run(() => this.image = image.src);
        this.storage.query("UPDATE verifyBL SET Thu = '" + this.image + "' WHERE id = 2").then((data) => {
        }, (error) => {
            console.log("ERROR -> " + JSON.stringify(error.err));
        });
    }, (error) => {
        alert(error);
    });
}

And when sending it via mailto it looks like:

(click)="mailIT('mailto:'+post.email +'?body=' +emailText + '&attachment='+imageSC)"

The body text will be send correctly but no attachment. I tried it with the base64 version, but no success either. The function on the page1.js looks like:

mailIT(passedMail) {
    window.location = passedMail;
}

And imsageSC is defined like:

onPageWillEnter() {
        this.storage.query("SELECT * FROM verifyBL").then((data) => {
            if(data.res.rows.length > 0) {
            this.emailText = data.res.rows.item(1).Sch;
            this.imageSC = data.res.rows.item(1).Thu;
        }
    }, (error) => {
        console.log("ERROR -> " + JSON.stringify(error.err));
    });
}

Solution

  • According to the the spec (RFC 6068), attachments cannot be attached to emails using the mailto: scheme. That's why your attachment=... is being ignored. If you want to add an attachment, you'll have to use another method. Here are two options. I haven't actually tested them, but I believe either would work:

    Using Cordova Email Plugin and Ionic Native

    (NOTE: this may not be stable.) First install the Cordova email plugin and also the ionic-native plugin from the console:

    $ ionic plugin add cordova-plugin-email-composer
    $ npm install --save ionic-native
    

    Then in your component:

    import {Component} from "@angular/core";
    import {NavController, Storage, SqlStorage} from "ionic-angular";
    import {EmailComposer} from "ionic-native";
    
    @Component({
        templateUrl: "build/pages/mypage/mypage.html"
    })
    export class MyPage {
    
        storage: Storage;
        emailText: string;
        imageSC: string;
    
        constructor(public nav: NavController) {
            this.storage = new Storage(SqlStorage);
            this.storage.query("SELECT * FROM verifyBL").then((data) => {
                if(data.res.rows.length > 0) {
                    this.emailText = data.res.rows.item(1).Sch;
                    this.imageSC = data.res.rows.item(1).Thu;
                }
            }, (error) => {
                console.log("ERROR -> " + JSON.stringify(error.err));
            });
        }
    
        mailIt() {
            EmailComposer.isAvailable().then((avail: boolean) => {
                if (available) {
                    let email = {
                        to: this.post.email, // not sure where you set this...
                        attachments: [
                            this.imageSC
                        ],
                        body: this.emailText,
                        subject: "Email with attachment",
                        isHtml: true
                    };
                    EmailComposer.open(email);
                }
            });
        }
    }
    

    Using Mailgun

    import {Component} from "@angular/core";
    import {NavController, Storage, SqlStorage} from "ionic-angular";
    import {Http, Request, RequestMethod, Headers, HTTP_PROVIDERS} from "@angular/http";
    
    @Component({
        templateUrl: "build/pages/mypage/mypage.html"
    })
    export class MyPage {
    
        storage: Storage;
        emailText: string;
        imageSC: string;
        mailgunUrl: string;
        mailgunApiKey: string;
    
        constructor(public nav: NavController, private http: Http) {
            this.storage = new Storage(SqlStorage);
            this.storage.query("SELECT * FROM verifyBL").then((data) => {
                if(data.res.rows.length > 0) {
                    this.emailText = data.res.rows.item(1).Sch;
                    this.imageSC = data.res.rows.item(1).Thu;
                }
            }, (error) => {
                console.log("ERROR -> " + JSON.stringify(error.err));
            });
            this.mailgunUrl = "YOUR_MAILGUN_URL";
            this.mailgunApiKey = window.btoa("api:key-MAILGUN_API_KEY_HERE");
        }
    
        mailIt() {
            let headers = new Headers();
            headers.append("Authorization", "Basic " + this.mailgunApiKey);
            headers.append("Content-Type", "application/x-www-form-urlencoded");
            this.http.request(new Request({
                method: RequestMethod.Post,
                url: "https://api.mailgun.net/v3/" + this.mailgunUrl + "/messages",
                body: "from=test@example.com&to=" + this.post.email + "&subject=Email+with+attachment&text=" + this.emailText,
                attachment: this.imageSC, // not sure about this, maybe [this.imageSC]
                headers: requestHeaders
            }))
            .subscribe(
                success => { console.log("Success", success);},
                error   => { console.log("Error",   error); }
            );
        }
    }