简体   繁体   English

从Android应用发送电子邮件

[英]Sending email from Android app

I am trying to a develop an android app that sends email using JavaMail. 我正在尝试开发一个使用JavaMail发送电子邮件的android应用。 I have tried the code bellow as console application and it works, but when I use in as an android app from the emulator it throws exception with no message. 我已经尝试将下面的代码作为控制台应用程序使用,并且可以正常工作,但是当我从模拟器中将其用作android应用程序时,它会抛出异常且不显示任何消息。 I have modified the manifest.xml and put 我已经修改了manifest.xml并把

<uses-permission android:name="android.permission.INTERNET" /> 

but it still doesn't work. 但它仍然不起作用。 The exception is thrown at message.setText("Welcome to JavaMail"); message.setText("Welcome to JavaMail");处引发异常message.setText("Welcome to JavaMail"); So please help me out! 所以请帮帮我!

I am using the mail.jar and activation.jar from Sun. 我正在使用Sun的mail.jaractivation.jar

Bellow is the full code on the ClickHandler. 波纹管是ClickHandler上的完整代码。

 public void btnSendClickHandler(View view)
   {
    try{

        String host = "smtp.gmail.com";
        String from = "Username@gmail.com";
        String pass = "Password";
        Properties props = System.getProperties();
        props.put("mail.smtp.starttls.enable", "true"); // added this line
        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");

        String[] to = {"toEmailAddress@gmail.com"}; // added this line

        Session session = Session.getDefaultInstance(props, null);

        MimeMessage message = new MimeMessage(session);
        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("sending in a group");
        message.setText("Welcome to JavaMail");//The exception is thrown here   

        Transport transport = session.getTransport("smtp");
        transport.connect(host, from, pass);
        transport.sendMessage(message, message.getAllRecipients());
        transport.close();
 } catch(Exception e){Toast.makeText(this, e.toString(),
        Toast.LENGTH_LONG).show();
                      }}

如果使用以下方式设置主体,也许可以解决该异常:

_multipart = new MimeMultipart();

BodyPart messageBodyPart = new MimeBodyPart();

messageBodyPart.setText("Welcome to JavaMail");

_multipart.addBodyPart(messageBodyPart);

message.setContent(_multipart);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM