G
Guest
Gast
ist es möglich eine mail in java zu versenden?
L-ectron-X hat gesagt.:Ja.
Du benötigst dazu mindestens die Klassen URL und URLConnection aus java.net
und die passenden Streamklassen aus java.io.
public MailSender(String m_sHostName, int m_iPort, String sender,
String reciever, String subject, String body) {
Date dDate = new Date();
DateFormat dFormat = DateFormat.getDateInstance(DateFormat.FULL,
Locale.GERMAN);
try { // Open port to server
smtpSocket = new Socket(m_sHostName, m_iPort);
os = new DataOutputStream(smtpSocket.getOutputStream());
is = new DataInputStream(smtpSocket.getInputStream());
if (smtpSocket != null && os != null && is != null) {
// Connection was made. Socket is ready for use.
System.out.println("Connected to SMTP server.");
try {
String hostname = new String();
try {
InetAddress addr = InetAddress.getLocalHost();
hostname = addr.getHostName();
} catch (UnknownHostException e) {
System.out.println("Could not get local hostname.");
}
System.out.println(is.readLine());
os.writeBytes("HELO " + hostname + "\r\n");
System.out.println(is.readLine());
// You will add the email address that the server
// you are using know you as.
os.writeBytes("MAIL From: <" + sender + ">\r\n");
System.out.println(is.readLine());
// To whom the email is going to.
os.writeBytes("RCPT To: <" + reciever + ">\r\n");
System.out.println(is.readLine());
// IF you want to send a CC then you will have to add this
// os.writeBytes("RCPT Cc: <theCC@anycompany.com>\r\n");
// Now we are ready to add the message and the
// header of the email to be sent out.
os.writeBytes("DATA\r\n");
System.out.println(is.readLine());
os.writeBytes("X-Mailer: Via Java\r\n");
os.writeBytes("DATE: " + dFormat.format(dDate) + "\r\n");
os.writeBytes("From: JavaAutoMailer <" + sender + ">\r\n");
os.writeBytes("To: <" + reciever + ">\r\n");
// Again if you want to send a CC then add this.
// os.writeBytes("Cc: CCDUDE
// <CCPerson@theircompany.com>\r\n");
// Here you can now add a BCC to the message as well
// os.writeBytes("RCPT Bcc:
// BCCDude<BCC@invisiblecompany.com>\r\n");
os.writeBytes("Subject: " + subject + "\r\n");
os.writeBytes(body + "\r\n");
os.writeBytes("\r\n.\r\n");
os.writeBytes("QUIT\r\n");
// Now send the email off and check the server reply.
// Was an OK is reached you are complete.
String responseline;
while ((responseline = is.readLine()) != null) { // System.out.println(responseline);
System.out.println(responseline);
if ((responseline.indexOf("Ok") != -1)
|| (responseline.indexOf("OK") != -1))
System.out.println("Email sent.");
break;
}
this.smtpSocket.close();
} catch (Exception e) {
System.out
.println("Cannot send email as an error occurred.");
}
}
} catch (Exception e) {
System.out.println("Host " + m_sHostName + " unknown");
}
}
DP hat gesagt.: