gpt4 book ai didi

java - 在 netbeans 错误中使用 javamail

转载 作者:行者123 更新时间:2023-11-30 08:48:15 25 4
gpt4 key购买 nike

我正在尝试在 Netbeans 中使用 javamail 函数,但一直出现错误

javax.mail.MessagingException: Could not connect to SMTP host: 10.101.3.229,  port: 25;
nested exception is:
java.net.ConnectException: Connection timed out: connect

我使用的代码是:

import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;

public class TESTINGemail {

public static void main(String [] args)
{
String to = "abcd@gmail.com";
String from = "web@gmail.com";

String host = "localhost";

Properties properties = System.getProperties();

properties.setProperty("mail.smtp.host", host);

Session session = Session.getDefaultInstance(properties);

try{
MimeMessage message = new MimeMessage(session);

message.setFrom(new InternetAddress(from));

message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));

message.setSubject("This is the Subject Line!");

message.setText("This is actual message");

Transport.send(message);
System.out.println("Sent message successfully....");
}catch (MessagingException mex) {
mex.printStackTrace();
}
}
}

我使用了一个教程,这基本上就是他们使用的代码。我曾尝试更改主机但每次都失败了。

最佳答案

如果您使用 gmail id 发送邮件,则不能使用本地主机,您必须使用 gmail 主机服务器地址“mail.smtp.host”,所以您试试这个。

import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;

public class MailSender {
public static void send (String to,String message1,String subject,String ss)
throws Exception {
String host ="smtp.gmail.com";
String from="from@gmail.com";
String password="Your password";
Properties props = System.getProperties();

props.put("mail.transport.protocol", "smtps");
props.put("mail.smtp.user", from);
props.put("mail.smtp.password", password);
props.put("mail.smtp.port", "465");
props.put("mail.smtps.auth", "true");
props.put("mail.smtp.starttls.enable","true");

props.put("mail.smtp.host", host);

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


MimeMessage message = new MimeMessage(session);
message.setFrom( new InternetAddress(from));
message.addRecipient( Message.RecipientType.TO, new InternetAddress(to));
message.setSubject(subject);
message.setText(message1);



Transport transport = session.getTransport("smtps");
transport.connect(host,from, password);
transport.sendMessage(message, message.getAllRecipients());
System.out.println("mail has been sent");
}


public static void main(String arg[]) throws Exception
{

MailSender m=new MailSender();
m.send("to@gmail.com", "hello ..", "test mail...","");
}
}

并禁用您的 PC 防病毒软件和防火墙,并在 Google 帐户设置中打开“访问安全性较低的应用程序”。

https://www.google.com/settings/security/lesssecureapps .

关于java - 在 netbeans 错误中使用 javamail,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32060669/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com