java - 如何在点击事件中发送电子邮件,而用户不会注意到在后台运行
问题描述
我想在后台发送电子邮件,以便用户在单击发送电子邮件按钮时看不到后台活动。我试图正确获取该功能,但我只能找到弹出电子邮件布局片段
private Context context;
private Session session;
//Information to send email
private String email;
private String subject;
private String message;
private String sender;
//Progress dialog to show while sending email
private ProgressDialog progressDialog;
//Class Constructor
public SendMail(Context context, String email, String subject, String message, String sender){
//Initializing variables
this.context = context;
this.email = email;
this.subject = subject;
this.message = message;
this.sender = sender;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
//Showing progress dialog while sending email
progressDialog = ProgressDialog.show(context,"Sending email to user","Please wait...",false,false);
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
//Dismissing the progress dialog
progressDialog.dismiss();
//Showing a success message
Toast.makeText(context,"Email Sent Successfully",Toast.LENGTH_LONG).show();
}
@Override
protected Void doInBackground(Void... params) {
//Creating properties
Properties props = new Properties();
//Configuring properties for gmail
//If you are not using gmail you may need to change the values
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
//Creating a new session
session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
//Authenticating the password
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(Config.EMAIL, Config.PASSWORD);
}
});
try {
//Creating MimeMessage object
MimeMessage mm = new MimeMessage(session);
try {
mm.setFrom(new InternetAddress("test@gmail.com",sender));
mm.setReplyTo(InternetAddress.parse("test@gmail.com",false));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
//Adding receiver
mm.addRecipient(Message.RecipientType.TO, new InternetAddress(email));
//Adding subject
mm.setSubject(subject);
//Adding message
mm.setText(message);
//Sending email
Transport.send(mm);
} catch (MessagingException e) {
e.printStackTrace();
}
return null;
}
}
解决方案
推荐阅读
- ios - 如何在 iOS 中将 base64 字符串发送到服务器?
- c# - asp.net C# Gridview 包含数据但只返回单元格值 = ""
- linux - 如何为我设计的 CPU 制作 Linux 操作系统?
- c++ - 为什么临时生命周期结束时程序没有崩溃?
- javascript - 谷歌分析事件跟踪不起作用
- sql-server - How to optimize where clause of SQL Server query
- python - 安装 Flask 应用程序
- laravel - 与多个中间表的多对多 Laravel Eloquent 关系
- performance - 具有两个 NUMA 节点的机器上的 MPICH2
- jquery - 全日历,天数悬停效果