【发布时间】:2014-10-18 12:29:08
【问题描述】:
我的服务器防火墙有问题。我正在尝试使用 sendmail 从我的服务器发送电子邮件,但是当防火墙被激活时,这是不可能的。我在日志中发现以下错误:
无法连接到主机,端口:mail.infomaniak.ch, 25;超时 -1
当我的防火墙被禁用时,一切正常并且我的邮件已发送。所以我尝试在防火墙的输出中打开端口 25,但没有任何改变我总是同样的问题。
这是我的代码:
public void envoyerMailSMTP(ArrayList<String> to, ArrayList<String> cc, ArrayList<String> bcc, String from, String subject, String body, String attachment, String attachmentName) throws Exception {
this.catalog = (Catalog)lookupEjb("CatalogLocal", true);
Properties props = new Properties();
props.put("mail.transport.protocol", "smtp");
//props.put("mail.smtp.port", "587");
props.put("mail.smtp.host", this.catalog.getFirst(this.catalog.findByKey("SMTP_HOST_NAME")).getCatalogValue());
props.put("mail.smtp.auth", "true");
Session mailSession = Session.getDefaultInstance(props);
// uncomment for debugging infos to stdout
// mailSession.setDebug(true);
try {
Transport transport = mailSession.getTransport();
MimeMessage message = new MimeMessage(mailSession);
// Ajout de l'expéditeur du mail
if(from != null && !from.isEmpty()){
message.setFrom(new InternetAddress(from));
}
// Ajout de(s) destinataire(s) du mail
for(String s : to){
message.addRecipient(Message.RecipientType.TO, new InternetAddress(s));
}
// Ajout de(s) destinataire(s) du mail en cc
if(cc != null && cc.size() > 0){
for(String s : cc){
message.addRecipient(Message.RecipientType.CC, new InternetAddress(s));
}
}
// Ajout de(s) destinataire(s) du mail en bcc
if(bcc != null && bcc.size() > 0){
for(String s : bcc){
message.addRecipient(Message.RecipientType.BCC, new InternetAddress(s));
}
}
// Set Subject: header field
message.setSubject(subject);
// Create the message part
BodyPart messageBodyPart = new MimeBodyPart();
// Fill the message
messageBodyPart.setText(body);
// Create a multipart message
Multipart multipart = new MimeMultipart();
// Set text message part
multipart.addBodyPart(messageBodyPart);
// Part two is attachment
messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(attachment);
messageBodyPart.setDataHandler(new DataHandler(source));
// Set the name of the attached file
messageBodyPart.setFileName(attachmentName);
multipart.addBodyPart(messageBodyPart);
// Send the complete message parts
message.setContent(multipart);
transport.connect(this.catalog.getFirst(this.catalog.findByKey("SMTP_HOST_NAME")).getCatalogValue(),
this.catalog.getFirst(this.catalog.findByKey("SMTP_AUTH_USER")).getCatalogValue(),
this.catalog.getFirst(this.catalog.findByKey("SMTP_AUTH_PWD")).getCatalogValue());
transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO));
transport.close();
}catch (MessagingException ex){
System.out.println(ex.getMessage());
System.out.println(ex.getStackTrace());
}
}
我也尝试修改我的代码以使用端口 587 并在防火墙上打开它,但效果并不好。
我有一台 Linux 服务器,我使用 ufw 作为防火墙。
有人可以帮我吗?
【问题讨论】:
-
您是否尝试过直接从命令行使用 sendmail?
... but it was better是什么意思?比什么更好,以什么方式更好? -
是的,我之前尝试过,邮件也没有在命令行中发送
-
好吧,那么我会说问题不在于您的 Java 代码,而在于您的系统或防火墙配置。
标签: java linux sendmail firewall