[英]Sending an mail in java using smtp
我正在嘗試發送電子郵件,但出現以下錯誤:
javax.mail.SendFailedException: Sending failed;
nested exception is:
javax.mail.MessagingException: Could not connect to SMTP host: 10.17.1.65, port: 25
首先測試netstat命令,看看主機是否響應。 如果是,那么您需要檢查主機上的電子郵件服務器/中繼。 您可以通過此鏈接http://www.mailradar.com/openrelay/對其進行測試
在這里,我分享了一個用於使用帶有多個附件的Gmail SSL發送郵件的類。 只需使用實際的gmail憑據更改gmailUsername和gmailPass。 並用您想要的地址更改往返地址。 在這里,我們已使用Gmail SSL smtp端口發送郵件。 您可以使用自己的郵件服務器詳細信息進行更改。
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
/**
Author Mridul Chatterjee
*/
import java.util.Properties;
import javax.mail.Message;
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 SendMail {
public static void main(String[] args) {
Properties props = new Properties();
props.put(”mail.smtp.host”, “smtp.gmail.com”);
props.put(”mail.smtp.socketFactory.port”, “465″);
props.put(”mail.smtp.socketFactory.class”,
“javax.net.ssl.SSLSocketFactory”);
props.put(”mail.smtp.auth”, “true”);
props.put(”mail.smtp.port”, “465″);
ArrayList fileNames = new ArrayList();
fileNames.add(”C:/Write.txt”);
fileNames.add(”C:/Write1.txt”);
fileNames.add(”C:/Write2.txt”);
fileNames.add(”C:/Write3.txt”);
fileNames.add(”C:/25148.jpg”);
Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(”gmailUsername”,”gmailPass”);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(”from@no-spam.com”));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(”tomail@mail.com”));
message.setSubject(”Testing Subject”);
message.setText(”Dear Mail Crawler,” +
“nn No spam to my email, please!”);
// multipart.addBodyPart(messageBodyPart);
// DataSource source = new FileDataSource(filename);
// messageBodyPart.setDataHandler(new DataHandler(source));
// messageBodyPart.setFileName(filename);
System.out.println(fileNames.size());
Multipart multipart = new MimeMultipart();
BodyPart messageBodyPart = new MimeBodyPart();
for(int i=0;i {
System.out.println(fileNames.get(i));
messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource((String)fileNames.get(i));
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName((String)fileNames.get(i));
multipart.addBodyPart(messageBodyPart);
//message.setContent(multipart);
}
//multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
Transport.send(message);
System.out.println(”Mail Sent Successfully….”);
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.