我如何从我的主Activity中调用JavaEmail类?

时间:2018-04-15 19:58:51

标签: java android class

这是我的android studio项目中单独的java类文件中的示例代码。 (我在此示例中仅保留了示例凭据,但我将其替换为我自己代码中的实际值)

package com.mytest.java;

import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class JavaEmail {

    Properties emailProperties;
    Session mailSession;
    MimeMessage emailMessage;

    public static void main(String args[]) throws AddressException,
            MessagingException {

        JavaEmail javaEmail = new JavaEmail();

        javaEmail.setMailServerProperties();
        javaEmail.createEmailMessage();
        javaEmail.sendEmail();
    }

    public void setMailServerProperties() {

        String emailPort = "587";//gmail's smtp port

        emailProperties = System.getProperties();
        emailProperties.put("mail.smtp.port", emailPort);
        emailProperties.put("mail.smtp.auth", "true");
        emailProperties.put("mail.smtp.starttls.enable", "true");

    }

    public void createEmailMessage() throws AddressException,
            MessagingException {
        String[] toEmails = { "joe@javapapers.com" };
        String emailSubject = "Java Email";
        String emailBody = "This is an email sent by JavaMail api.";

        mailSession = Session.getDefaultInstance(emailProperties, null);
        emailMessage = new MimeMessage(mailSession);

        for (int i = 0; i < toEmails.length; i++) {
            emailMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(toEmails[i]));
        }

        emailMessage.setSubject(emailSubject);
        emailMessage.setContent(emailBody, "text/html");//for a html email
        //emailMessage.setText(emailBody);// for a text email

    }

    public void sendEmail() throws AddressException, MessagingException {

        String emailHost = "smtp.gmail.com";
        String fromUser = "your emailid here";//just the id alone without @gmail.com
        String fromUserEmailPassword = "your email password here";

        Transport transport = mailSession.getTransport("smtp");

        transport.connect(emailHost, fromUser, fromUserEmailPassword);
        transport.sendMessage(emailMessage, emailMessage.getAllRecipients());
        transport.close();
        System.out.println("Email sent successfully.");
    }

}

我在onCreate上尝试了什么:

public class BrowseActivity extends AppCompatActivity {

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        JavaEmail myEmailSender = new JavaEmail();
    }
...
}

JavaEmail永远不会被发送。我在文件中添加了一个日志,但是我没有在logcat中看到它,因为我猜它甚至没有调用构造函数。这对于我对调用类的理解是一个简单的问题,但我还没有得到它。 JavaEmail的主要方法接受args参数,我认为我不需要这样做,如果我从JavaEmail类中删除主args,我就像这样更改onCreate调用

JavaEmail.main();

给出:未处理的异常:编译前的javax.mail.MessagingException错误。

感谢您的帮助。

2 个答案:

答案 0 :(得分:0)

我在swing应用程序中做了同样的事情,我创建了一个名为SendEmail的类,它有一个生成otp并发送它的方法。

    class SendEmail
    {
     String from = "username";  // GMail user name
     String pass = "password";
     public void sendOTPEmail(String email)
    {
        String otp=OTP.generate();
        String to[] = {email}; // list of recipient email addresses

        String subject = "One Time Password";
        String body = "<html>\n" +
                        "  <body>\n" +
                        "    <div style='font-size:17px; font-family:cambria'>\n" +
                        "    OTP is generated for changing password of JavaLearn System acount associated with this email.<br><br>\n" +
                        "      Your OTP is:<br>\n" +
                        "     <center>\n" +
                        "      <div style='color:red;font-size:18px; font-family:cambria; border:2px solid black'>\n" +
                        "           \n" +otp+
                        "      </div>\n" +
                        "       </center>\n" +
                        "    </div>\n" +
                        "    </body>\n" +
                        "  </html>";

        Properties props = System.getProperties();
        String host = "smtp.gmail.com";
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.user", from);
        props.put("mail.smtp.password", pass);
        props.put("mail.smtp.port", "587");
        props.put("mail.smtp.auth", "true");

        Session session = Session.getDefaultInstance(props);
        MimeMessage message = new MimeMessage(session);

        try {
            message.setFrom(new InternetAddress(from));
            InternetAddress[] toAddress = new InternetAddress[to.length];

            // To get the array of addresses
            for( int i = 0; i < to.length; i++ ) {
                toAddress[i] = new InternetAddress(to[i]);
            }

            for( int i = 0; i < toAddress.length; i++) {
                message.addRecipient(Message.RecipientType.TO, toAddress[i]);
            }

            message.setSubject(subject);
            message.setContent(body, "text/html; charset=utf-8");

            Transport transport = session.getTransport("smtp");
            transport.connect(host, from, pass);
            transport.sendMessage(message, message.getAllRecipients());
            transport.close();

            }
     }


从另一个类我刚刚调用了这样一个方法:

    String to="abc@gmail.com";
    Thread t1=new Thread(()->{new SendEmail().sendOTPEmail(to);});
    t1.start();

答案 1 :(得分:0)

Java是一种深层语言。多年没使用它,从来都不是专家。无论如何,感谢这篇伟大的文章,我得到了我需要的工作。没什么特别的,但它会作为我的考试学习科目。

像迈克尔在他的评论中发表的那样,它必须在后台完成,我只是分配变量,这对于构造函数来说还不够。

我没有必要通过在build.gradle文件中的现有代码下面添加以下代码来加载任何jar文件来引用API :(我还必须使用自1.6以来的1.6.0版本的库。 1坠毁)

android {
    packagingOptions {
        //pickFirst 'META-INF/LICENSE.txt' // picks the JavaMail license file
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/mimetypes.default'
        exclude 'META-INF/mailcap.default'
    }
}

repositories {
    jcenter()
    maven {
        url "https://maven.java.net/content/groups/public/"
    }
}

dependencies {
    //Problem with compiling 1.6.1 so using older version
    //https://stackoverflow.com/questions/49575982/after-update-to-android-studio-3-1-the-project-does-not-build-program-type-alre
    implementation 'com.sun.mail:android-mail:1.6.0'
    implementation 'com.sun.mail:android-activation:1.6.0'
}

https://javapapers.com/android/android-email-app-with-gmail-smtp-using-javamail/