java - 使用 java 代码发送电子邮件
问题描述
早上好 。我有个问题 。我想使用 eclipse oxygen.3 March 2018 通过 Gmail 发送电子邮件。我用了两个罐子:mail-1.4.7 和activation 1.1.1。而且我允许对我的 Gmail 帐户进行不太安全的访问。这是我的代码:
package Login_sys;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
public class EmailSend {
final String emailSMTPserver = "smtp.gmail.com";
final String emailServerPort = "587";
String receiverEmail = null;
String emailSubject = null;
String emailBody = null;
String from = null ;
String password = null ;
public EmailSend(String from,String password,String subject ,String message,String to)
{
this.from = from ;
this.password = password ;
this.emailSubject = subject ;
this.emailBody = message ;
this.receiverEmail = to ;
Properties props = System.getProperties();
props.put("mail.smtp.user", from);
props.put("mail.smtp.host", emailSMTPserver);
props.put("mail.smtp.port", emailServerPort);
props.put("mail.smtp.starttls.enable","true");
props.put("mail.smtp.password", password);
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.socketFactory.port", emailServerPort);
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
SecurityManager security = System.getSecurityManager();
try
{
Authenticator auth = new SMTPAuthenticator();
Session session = Session.getInstance(props, auth);
Message msg = new MimeMessage(session);
msg.setText(emailBody);
msg.setSubject(emailSubject);
msg.setFrom(new InternetAddress(from));
msg.addRecipient(Message.RecipientType.TO,
new InternetAddress(receiverEmail));
Transport.send(msg);
System.out.println("send successfully");
} catch (Exception ex) {
System.err.println("Error occurred while sending.!");
}
}
private class SMTPAuthenticator extends javax.mail.Authenticator {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(from , password);
}
}}
我从其他类调用它:
EmailSend f = new EmailSend ("******@gmail.com","*****","Testing","testin
email","****@gmail.com");
它总是打印:发送时发生错误。!. 我不知道我的错误在哪里
解决方案
您设置了错误的端口号。将其更改为:
final String emailServerPort = "465";
Gmail SMTP 端口 (TLS):587
Gmail SMTP 端口 (SSL):465
推荐阅读
- go - 将 cloudevents 格式的数据发送到 Kafka 主题
- postgresql - 移动 docker-compose.yml 创建一个新的 postgres 数据库
- matomo - 错误:在模块“API”中找不到操作“Iframe”
- azure - 与 Azure DevOps Server 2020 共享 Azure DevOps 门户
- css - 消除图像和行边界之间的间隙
- database - Oracle 中的批量选择和插入
- python - Python,Pandas 数据透视表:如何获得 SubCount 的总和?
- sql - 显示列中重复项的单个结果并包括剩余的表结果
- javascript - 如何以角度在 I-Frame 和父窗口之间进行通信
- three.js - 如何添加一个对象取决于三个js中的线(墙)?