不使用SMTP意图发送邮件机器人 [英] Sending mail in android without intents using SMTP

查看:414
本文介绍了不使用SMTP意图发送邮件机器人的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好我正在开发一个Android应用程序,它会发送邮件上点击一个按钮。 code工作在第一,但由于某些原因,它不工作了。任何人都可以请帮我这个? xyz@outlook.com是收件人。 abc@gmail.com是发送者。 我已经很难codeD的主题和邮件正文。

 包com.example.clc_construction;
进口的java.io.File;
进口java.io.UnsupportedEncodingException;
进口java.util.Properties;
进口的javax.activati​​on.DataHandler;
进口javax.activati​​on.DataSource;
进口javax.activati​​on.FileDataSource;
进口javax.mail.Message;
进口javax.mail.MessagingException的;
进口javax.mail.Multipart;
进口javax.mail.PasswordAut​​hentication;
进口javax.mail.Session的;
进口javax.mail.Transport;
进口javax.mail.internet.AddressException;
进口javax.mail.internet.InternetAddress;
进口javax.mail.internet.MimeBodyPart;
进口的javax.mail.internet.MimeMessage;
进口javax.mail.internet.MimeMultipart;
进口android.app.Activity;
进口android.app.ProgressDialog;
进口android.content.Intent;
进口android.graphics.Bitmap;
进口android.os.AsyncTask;
进口android.os.Bundle;
进口android.os.Environment;


公共类电子邮件扩展活动
{
公共字符串jobNo;
公共字符串teamNo;
私有静态最后字符串username =abc@gmail.com;
私有静态最后字符串密码=000000;
私有静态最后弦乐EMAILID =xyz@outlook.com;
私有静态最后弦乐主题=照片;
私有静态最后字符串消息=你好;
私人多部分多部分=新MimeMultipart的();
私人MimeBodyPart messageBodyPart =新MimeBodyPart();
公共文件媒体文件;

@覆盖
保护无效的onCreate(包savedInstanceState)
{
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.camera_screen);
    意向意图= getIntent();
    jobNo = intent.getStringExtra(Job_No);
    teamNo = intent.getStringExtra(Team_No);
    Sendmail的(EMAILID,主题,邮件);

}
私人无效的sendmail(字符串email,字符串主题,字符串消息体)
 {
        会话会话= createSessionObject();

        尝试 {
            消息消息= createMessage(电子邮件,主题,消息体,会话);
            新SendMailTask​​()执行(消息);
        }
        赶上(是AddressException E)
        {
            e.printStackTrace();
        }
        赶上(MessagingException E)
        {
            e.printStackTrace();
        }
        赶上(UnsupportedEncodingException E)
        {
            e.printStackTrace();
        }
    }


私人会议createSessionObject()
{
    属性属性=新的属性();
    properties.put(mail.smtp.auth,真);
    properties.put(mail.smtp.starttls.enable,真);
    properties.put(mail.smtp.host,smtp.gmail.com);
    properties.put(mail.smtp.port,587);

    返回Session.getInstance(属性,新javax.mail.Authenticator()
    {
        受保护的PasswordAut​​hentication的getPasswordAut​​hentication()
        {
            返回新的PasswordAut​​hentication(用户名,密码);
        }
    });
}

悄悄话createMessage(字符串email,字符串主题,字符串消息体,届届)抛出

MessagingException,UnsupportedEncodingException
{
    消息消息=新的MimeMessage(会议);
    message.setFrom(新网际(xzy@outlook.com,函数naveed库雷希));
    message.addRecipient(Message.RecipientType.TO,新的网际(电子邮件,电子邮件));
    message.setSubject(学科);
    message.setText(消息体);
    返回消息;
}



公共类SendMailTask​​扩展的AsyncTask<消息,虚空,虚空>
{
    私人ProgressDialog progressDialog;

    @覆盖
    在preExecute保护无效()
    {
        super.on preExecute();
        progressDialog = ProgressDialog.show(Email.this,请稍等,发送邮件,真,假);
    }

    @覆盖
    保护无效onPostExecute(虚空避免)
    {
        super.onPostExecute(避免);
        progressDialog.dismiss();
    }

    保护无效doInBackground(javax.mail.Message ...消息)
    {
        尝试
        {
            Transport.send(消息[0]);
        }赶上(MessagingException E)
        {
            e.printStackTrace();
        }
        返回null;
    }
}
}
 

解决方案

把你的清单文件,

 <使用-权限的Andr​​oid:名称=android.permission.ACCESS_NETWORK_STATE/>
 

检查,如果您有互联网连接,

 公共布尔isOnline(){
    ConnectivityManager厘米=
        (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
    的NetworkInfo的NetInfo = cm.getActiveNetworkInfo();
    如果(NetInfo的= NULL和放大器;!&安培; netInfo.isConnectedOrConnecting()){
        返回true;
    }
    返回false;
}
 

和finnaly使用code发送电子邮件

 最后字符串username =username@gmail.com;
最终的字符串密码=密码;

属性道具=新特性();
props.put(mail.smtp.auth,真);
props.put(mail.smtp.starttls.enable,真);
props.put(mail.smtp.host,smtp.gmail.com);
props.put(mail.smtp.port,587);

会话会话= Session.getInstance(道具,
  新javax.mail.Authenticator(){
    受保护的PasswordAut​​hentication的getPasswordAut​​hentication(){
        返回新的PasswordAut​​hentication(用户名,密码);
    }
  });
    尝试 {
        消息消息=新的MimeMessage(会议);
        message.setFrom(新网际(from-email@gmail.com));
        message.setRecipients(Message.RecipientType.TO,
            InternetAddress.parse(to-email@gmail.com));
        message.setSubject(测试主题);
        message.setText(亲爱的邮件履带
            +\ñ\ N无垃圾邮件到我的邮箱,请!);

        MimeBodyPart messageBodyPart =新MimeBodyPart();

        多部分多部分=新MimeMultipart的();

        messageBodyPart =新MimeBodyPart();
        字符串文件=文件的路径要附加;
        字符串文件名=attachmentName
        数据源源=新FileDataSource(文件);
        messageBodyPart.setDataHandler(新的DataHandler(源));
        messageBodyPart.setFileName(文件名);
        multipart.addBodyPart(messageBodyPart);

        message.setContent(多部分);

        Transport.send(消息);

        的System.out.println(完成);

    }赶上(MessagingException E){
        抛出新的RuntimeException(E);
    }
 

Hi I am developing an android app which will send mail on click of a button. Code worked at first but due to some reason its not working now. Could anyone please help me with this? xyz@outlook.com is the recipient. abc@gmail.com is the sender. I have hard coded the subject and the body of the mail.

package com.example.clc_construction;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import android.app.Activity;
import android.app.ProgressDialog;  
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;


public class Email extends Activity
{
public String jobNo;
public String teamNo;
private static final String username = "abc@gmail.com";
private static final String password = "000000";
private static final String emailid = "xyz@outlook.com";
private static final String subject = "Photo";
private static final String message = "Hello";
private Multipart multipart = new MimeMultipart();
private MimeBodyPart messageBodyPart = new MimeBodyPart();
public File mediaFile;

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.camera_screen);
    Intent intent = getIntent();
    jobNo = intent.getStringExtra("Job_No");
    teamNo = intent.getStringExtra("Team_No"); 
    sendMail(emailid,subject,message);

}
private void sendMail(String email, String subject, String messageBody)
 {
        Session session = createSessionObject();

        try {
            Message message = createMessage(email, subject, messageBody, session);
            new SendMailTask().execute(message);
        }
        catch (AddressException e)
        {
            e.printStackTrace();
        }
        catch (MessagingException e)
        {
            e.printStackTrace();
        }
        catch (UnsupportedEncodingException e)
        {
            e.printStackTrace();
        }
    }


private Session createSessionObject()
{
    Properties properties = new Properties();
    properties.put("mail.smtp.auth", "true");
    properties.put("mail.smtp.starttls.enable", "true");
    properties.put("mail.smtp.host", "smtp.gmail.com");
    properties.put("mail.smtp.port", "587");

    return Session.getInstance(properties, new javax.mail.Authenticator()
    {
        protected PasswordAuthentication getPasswordAuthentication()
        {
            return new PasswordAuthentication(username, password);
        }
    });
}

private Message createMessage(String email, String subject, String messageBody, Session session) throws 

MessagingException, UnsupportedEncodingException
{
    Message message = new MimeMessage(session);
    message.setFrom(new InternetAddress("xzy@outlook.com", "Naveed Qureshi"));
    message.addRecipient(Message.RecipientType.TO, new InternetAddress(email, email));
    message.setSubject(subject);
    message.setText(messageBody);
    return message;
}



public class SendMailTask extends AsyncTask<Message, Void, Void>
{
    private ProgressDialog progressDialog;

    @Override
    protected void onPreExecute()
    {
        super.onPreExecute();
        progressDialog = ProgressDialog.show(Email.this, "Please wait", "Sending mail", true, false);
    }

    @Override
    protected void onPostExecute(Void aVoid)
    {
        super.onPostExecute(aVoid);
        progressDialog.dismiss();
    }

    protected Void doInBackground(javax.mail.Message... messages)
    {
        try
        {
            Transport.send(messages[0]);
        } catch (MessagingException e)
        {
            e.printStackTrace();
        }
        return null;
    }
}
}

解决方案

Put in your manifest file,

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

check if you have internet connection,

public boolean isOnline() {
    ConnectivityManager cm =
        (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    if (netInfo != null && netInfo.isConnectedOrConnecting()) {
        return true;
    }
    return false;
}

and finnaly use this code to send email

final String username = "username@gmail.com";
final String password = "password";

Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");

Session session = Session.getInstance(props,
  new javax.mail.Authenticator() {
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(username, password);
    }
  });
    try {
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress("from-email@gmail.com"));
        message.setRecipients(Message.RecipientType.TO,
            InternetAddress.parse("to-email@gmail.com"));
        message.setSubject("Testing Subject");
        message.setText("Dear Mail Crawler,"
            + "\n\n No spam to my email, please!");

        MimeBodyPart messageBodyPart = new MimeBodyPart();

        Multipart multipart = new MimeMultipart();

        messageBodyPart = new MimeBodyPart();
        String file = "path of file to be attached";
        String fileName = "attachmentName"
        DataSource source = new FileDataSource(file);
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName(fileName);
        multipart.addBodyPart(messageBodyPart);

        message.setContent(multipart);

        Transport.send(message);

        System.out.println("Done");

    } catch (MessagingException e) {
        throw new RuntimeException(e);
    }

这篇关于不使用SMTP意图发送邮件机器人的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆