react native android设置邮箱,进行邮件发送
react native android设置邮箱,进行邮件发送
-
引入发送邮件的架包。
在build.gradle 的dependencies 下引入://发送邮件的依赖implementation 'com.sun.mail:android-mail:1.6.7'implementation 'com.sun.mail:android-activation:1.6.7'
-
导入EmailSender类
import android.widget.Toast;import java.util.Properties;import javax.mail.Authenticator;import javax.mail.Message;import javax.mail.MessageRemovedException;import javax.mail.MessagingException;import javax.mail.PasswordAuthentication;import javax.mail.Session;import javax.mail.Transport;import javax.mail.internet.InternetAddress;import javax.mail.internet.MimeMessage;public class EmailSender {private String username;private String password;private String host;private String port;public EmailSender(String username,String password,String host,String port){this.username = username;this.password = password;this.host = host;this.port = port;}public void sendEmail(String to, String subject , String text){Properties properties = new Properties();properties.put("mail.smtp.auth",true);properties.put("mail.smtp.starttls.enable",true);properties.put("mail.smtp.host",host);properties.put("mail.smtp.port",port);Session session = Session.getInstance(properties, new Authenticator() {@Overrideprotected PasswordAuthentication getPasswordAuthentication() {return new PasswordAuthentication(username,password);}});try {Message message = new MimeMessage(session);message.setFrom(new InternetAddress(username));message.setRecipients(Message.RecipientType.TO,InternetAddress.parse(to));message.setSubject(subject);message.setText(text);Transport.send(message);} catch (MessagingException e){e.printStackTrace();}}}
-
在NativeModule 中调用。
username:账户名、邮箱
password:密码
host:主机
port:端口
to:发送的邮箱
subject:主题
text:内容
@ReactMethodpublic void sendEmail(String username,String password,String host,String port,String to,String subject,String text) {new Thread(new Runnable() {@Overridepublic void run() {EmailSender emailSender = new EmailSender(username,password,host,port);emailSender.sendEmail(to,subject,text);}}).start();}