使用java mail API从企业Outlook发送电子邮件时出现以下错误。
javax.mail.MessagingException: Could not connect to SMTP host: smtp.mycompany.net.au, port: 25;
nested exception is:
java.net.ConnectException: Connection refused: connect
我可以使用我的机器的相同端口远程登录服务器。问题的根本原因可能是什么?
用于发送电子邮件的代码是 -
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", mysmtpserver);
props.put("mail.smtp.port", myport);
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(fromEmailAddress));
message.setRecipients(Message.RecipientType.BCC, addressTo);
message.setSubject(emailSubject);
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setHeader("Content-Type", "text/html;charset=UTF-8");
messageBodyPart.setHeader("Content-Transfer-Encoding", "quoted-printable");
messageBodyPart.setContent(emailBody, "text/html;charset=UTF-8");
Multipart multipart = new MimeMultipart();
//part 1-add html part
multipart.addBodyPart(messageBodyPart);
messageBodyPart = new MimeBodyPart();
String filename = reportFilePath.trim();
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
赞赏解决它的任何帮助。
由于 利宾
答案 0 :(得分:0)
java.net.ConnectException:连接被拒绝:由于以下原因导致连接错误被抛出:
感谢您提供代码。请求应用以下代码。它很容易理解,也很好用。 100%测试
import java.io.*;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.mail.event.*;
import java.net.*;
import javax.activation.*;
public class SendEmail extends ConfigProperties{
public static void send(String from, String to, String subject, String content) throws AddressException, MessagingException{
ErrorCheck ec = new ErrorCheck();
String error = "";
try{
error = ec.error();
String smtp = getPropVal("SMTP");
String host = getPropVal("HOST");
Properties props=new Properties();
props.put(smtp,host);
Session session1 = Session.getDefaultInstance(props,null);
Message msg =new MimeMessage(session1);
msg.setHeader("Content-Type", "text/plain; charset=UTF-8");
msg.setHeader("Content-Transfer-Encoding", "quoted-printable");
msg.setFrom(new InternetAddress(from));
msg.setRecipients(Message.RecipientType.TO,InternetAddress.parse(to,false));
msg.setSubject(subject);
msg.setContent(content,"text/html; charset=UTF-8");
Transport.send(msg);
}catch(Exception e){
ec.errorMsg(error+"SendEmail.send()", e);
}
}
}