【问题标题】:Send mail via SMTP with Cordova使用 Cordova 通过 SMTP 发送邮件
【发布时间】:2016-06-05 13:29:28
【问题描述】:

我需要使用 Cordova 通过 SMTP 发送电子邮件。我可以使用哪个插件来完成这项任务?我已经用过cordova-plugin-composer之类的插件,但是插件会打开手机的应用邮件(例如gmail),我需要直接从de app发送邮件。

谢谢你(并帮助 x.x)

【问题讨论】:

    标签: android cordova email smtp


    【解决方案1】:

    第一步:在项目类路径中添加cordova.jar

    第 2 步:在 assets/www/js 文件夹中添加 cordova.js。

    第 3 步:创建一个名为 EmailComoposer.java 的新 Java 类

    package com.dinesh.pb;
    import org.apache.cordova.api.Plugin;
    import org.apache.cordova.api.PluginResult;
    import org.apache.cordova.api.PluginResult.Status;
    import org.json.JSONArray;
    import org.json.JSONException;
    import android.annotation.SuppressLint;
    import android.content.Intent;
    import android.text.Html;
    import com.dinesh.pb.utility.Mail;
    
    @SuppressLint("ParserError")
    public class EmailComposer extends Plugin {
    public final String ACTION_SEND_EMAIL = "sendEmail";
    
     @Override
     public PluginResult execute(String action, JSONArray arg1, String callbackId) {
     PluginResult result = new PluginResult(Status.INVALID_ACTION);
     if (action.equals(ACTION_SEND_EMAIL)) {
     try {
     String message = arg1.getString(0);
     this.sendEmailViaGmail(message);
     result = new PluginResult(Status.OK);
    
     }
     catch (JSONException ex) {
     result = new PluginResult(Status.JSON_EXCEPTION, ex.getMessage());
     } catch (Exception e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
     } 
     }
     return result;
     }
    
     private void sendEmailViaGmail(String body) throws Exception{
     Mail m = new Mail("From_email_address@gmail.com", "your password");
     String[] toArr = {"TO_EMAIL_ADDRESS@gmail.com"};
     m.set_to(toArr);
     m.set_from("FROM_EMAIL_ADDRESS@gmail.com");
     m.set_body(body);
     m.set_subject("TEST SUBJECT");
     boolean sendFlag = m.send();
    
     }
    
    }
    

    步骤 4. 将此 Mail.java 复制到您选择的包中。我的包名是 com.dinesh.pb.utility。

    package com.dinesh.pb.utility;
    import java.util.Date;
    import java.util.Properties;
    import javax.activation.CommandMap;
    import javax.activation.DataHandler;
    import javax.activation.DataSource;
    import javax.activation.FileDataSource;
    import javax.activation.MailcapCommandMap;
    import javax.mail.BodyPart;
    import javax.mail.Multipart;
    import javax.mail.PasswordAuthentication;
    import javax.mail.Session;
    import javax.mail.Transport;
    import javax.mail.internet.InternetAddress;
    import javax.mail.internet.MimeBodyPart;
    import javax.mail.internet.MimeMessage;
    import javax.mail.internet.MimeMultipart;
    public class Mail extends javax.mail.Authenticator { 
     private String _user; 
     private String _pass; 
    
     private String[] _to; 
     private String _from; 
    
     private String _port; 
     private String _sport; 
    
     private String _host; 
    
     private String _subject; 
     private String _body; 
    
     private boolean _auth; 
    
     private boolean _debuggable; 
    
     private Multipart _multipart; 
    
     public Mail() { 
     _host = "smtp.gmail.com"; // default smtp server 
     _port = "465"; // default smtp port 
     _sport = "465"; // default socketfactory port 
    
     _user = ""; // username 
     _pass = ""; // password 
     _from = ""; // email sent from 
     _subject = ""; // email subject 
     _body = ""; // email body 
    
     _debuggable = false; // debug mode on or off - default off 
     _auth = true; // smtp authentication - default on 
    
     _multipart = new MimeMultipart(); 
    
     // There is something wrong with MailCap, javamail can not find a handler for the multipart/mixed part, so this bit needs to be added. 
     MailcapCommandMap mc = (MailcapCommandMap) CommandMap.getDefaultCommandMap(); 
     mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html"); 
     mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml"); 
     mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain"); 
     mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed"); 
     mc.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822"); 
     CommandMap.setDefaultCommandMap(mc); 
     } 
    
     public Mail(String user, String pass) { 
     this(); 
    
     _user = user; 
     _pass = pass; 
     } 
    
     public boolean send() throws Exception { 
     Properties props = _setProperties(); 
    
     if(!_user.equals("") && !_pass.equals("") && _to.length > 0 && !_from.equals("") && !_subject.equals("") && !_body.equals("")) { 
     Session session = Session.getInstance(props, this); 
    
     MimeMessage msg = new MimeMessage(session); 
    
     msg.setFrom(new InternetAddress(_from)); 
    
     InternetAddress[] addressTo = new InternetAddress[_to.length]; 
     for (int i = 0; i < _to.length; i++) { 
     addressTo[i] = new InternetAddress(_to[i]); 
     } 
     msg.setRecipients(MimeMessage.RecipientType.TO, addressTo); 
    
     msg.setSubject(_subject); 
     msg.setSentDate(new Date()); 
    
     // setup message body 
     BodyPart messageBodyPart = new MimeBodyPart(); 
     messageBodyPart.setText(_body); 
     _multipart.addBodyPart(messageBodyPart); 
    
     // Put parts in message 
     msg.setContent(_multipart); 
    
     // send email 
     Transport.send(msg); 
    
     return true; 
     } else { 
     return false; 
     } 
     } 
    
     public void addAttachment(String filename) throws Exception { 
     BodyPart messageBodyPart = new MimeBodyPart(); 
     DataSource source = new FileDataSource(filename); 
     messageBodyPart.setDataHandler(new DataHandler(source)); 
     messageBodyPart.setFileName(filename); 
    
     _multipart.addBodyPart(messageBodyPart); 
     } 
    
     public String[] get_to() {
     return _to;
     }
    public void set_to(String[] _to) {
     this._to = _to;
     }
    public String get_from() {
     return _from;
     }
    public void set_from(String _from) {
     this._from = _from;
     }
    public String get_body() {
     return _body;
     }
    public void set_body(String _body) {
     this._body = _body;
     }
    @Override 
     public PasswordAuthentication getPasswordAuthentication() { 
     return new PasswordAuthentication(_user, _pass); 
     } 
    
     private Properties _setProperties() { 
     Properties props = new Properties(); 
    
     props.put("mail.smtp.host", _host); 
    
     if(_debuggable) { 
     props.put("mail.debug", "true"); 
     } 
    
     if(_auth) { 
     props.put("mail.smtp.auth", "true"); 
     } 
    
     props.put("mail.smtp.port", _port); 
     props.put("mail.smtp.socketFactory.port", _sport); 
     props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); 
     props.put("mail.smtp.socketFactory.fallback", "false"); 
    
     return props; 
     }
    public String get_subject() {
     return _subject;
     }
    public void set_subject(String _subject) {
     this._subject = _subject;
     }
    
     // more of the getters and setters ….. 
     }
    

    第 5 步:更新 config.xml 并添加有关新插件类 EmailComposer.java 的详细信息。我的看起来像这样 - 。请使用您的包路径更新包名称 value=”com.dinesh.pb.EmailComposer”。

    <?xml version="1.0" encoding="utf-8"?> 
    <cordova>
        <access origin="http://127.0.0.1*"/> <!-- allow local pages --> 
        <access origin=".*"/> 
        <log level="DEBUG"/>
        <preference name="useBrowserHistory" value="false" />
        <preference name="exit-on-suspend" value="false" />
    <plugins>
        <plugin name="App" value="org.apache.cordova.App"/>
        <plugin name="Geolocation" value="org.apache.cordova.GeoBroker"/>
        <plugin name="Device" value="org.apache.cordova.Device"/>
        <plugin name="Accelerometer" value="org.apache.cordova.AccelListener"/>
        <plugin name="Compass" value="org.apache.cordova.CompassListener"/>
        <plugin name="Media" value="org.apache.cordova.AudioHandler"/>
        <plugin name="Camera" value="org.apache.cordova.CameraLauncher"/>
        <plugin name="Contacts" value="org.apache.cordova.ContactManager"/>
        <plugin name="File" value="org.apache.cordova.FileUtils"/>
        <plugin name="NetworkStatus" value="org.apache.cordova.NetworkManager"/>
        <plugin name="Notification" value="org.apache.cordova.Notification"/>
        <plugin name="Storage" value="org.apache.cordova.Storage"/>
        <plugin name="Temperature" value="org.apache.cordova.TempListener"/>
        <plugin name="FileTransfer" value="org.apache.cordova.FileTransfer"/>
        <plugin name="Capture" value="org.apache.cordova.Capture"/>
        <plugin name="Battery" value="org.apache.cordova.BatteryListener"/>
        <plugin name="SplashScreen" value="org.apache.cordova.SplashScreen"/>
        <plugin name="Echo" value="org.apache.cordova.Echo" />
        <plugin name="EmailComposer" value="com.dinesh.pb.EmailComposer"/>
     </plugins>
    </cordova>
    

    第 6 步:创建一个名为 email.js 的新 javascript 文件

    var EmailComposer = function(){};
    /*
    cordova.addConstructor(function() {
        cordova.addPlugin("emailcomposer", new EmailComposer());
    });
    */
    EmailComposer.prototype.send = function (message){
    console.log("Calling the send message");
    cordova.exec(function(){ alert('feedback sent')}, 
        function(){ alert('feedback was not sent')}, 
        'EmailComposer', 
        'sendEmail', 
        [message]);
    }
    function sendFeedback(){
        window.EmailComposer.prototype.send("My message body");
    }
    

    现在正如我之前提到的,我使用的是 cordova-2.1.0.js/jar 文件,最新版本和旧版本 (cordova-1.9.0) 之间存在细微差别。如果您使用的是旧版本,则需要取消对 cordova.addConstructorabove 部分的注释,而不是调用

    window.EmailComposer.prototype.send("My message body");
    Use this:
    window.plugins.emailComposer.prototype.send(body);
    

    如果你不使用它,那么你可能会得到一个错误,说 window.plugins 没有定义。如果您遇到此类问题,请使用 firebug 并查看“window”变量下定义了哪些变量。

    注意名为“feedback()”的方法。我只是通过从用户反馈文本框中捕获输入来将用户文本作为消息正文传递。为简单起见,我刚刚粘贴了一个默认的电子邮件正文。

    第 7 步:在 index.html 文件中包含 js 文件

    // <!–[CDATA[
    javascript" src="js/email.js">
    // ]]>
    

    第 8 步:在 index.html 中包含 cordova js 文件

    // <!–[CDATA[
    javascript" src="js/cordova-2.1.0.js">
    // ]]>
    

    步骤 9:在 libs 文件夹中添加三个 Java 邮件 api 的 jar 文件——Activation.jar、Mail.jar 和 Additional.jar,并将其添加到类路径中。您可以在此处查看这些文件。

    干杯!!

    【讨论】:

      猜你喜欢
      • 2014-03-05
      • 1970-01-01
      • 2012-09-10
      • 2010-12-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-03
      相关资源
      最近更新 更多