Java/Email/Email Client
Версия от 18:01, 31 мая 2010; (обсуждение)
Содержание
Java Mail POP3 Client
import java.util.Properties;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Store;
public class MainClass {
public static void main(String[] args) throws Exception {
Properties props = new Properties();
String host = "yourHost.edu";
String username = "userName";
String password = "mypassword";
String provider = "pop3";
Session session = Session.getDefaultInstance(props, null);
Store store = session.getStore(provider);
store.connect(host, username, password);
Folder inbox = store.getFolder("INBOX");
if (inbox == null) {
System.out.println("No INBOX");
System.exit(1);
}
inbox.open(Folder.READ_ONLY);
Message[] messages = inbox.getMessages();
for (int i = 0; i < messages.length; i++) {
System.out.println("Message " + (i + 1));
messages[i].writeTo(System.out);
}
inbox.close(false);
store.close();
}
}
Java Mail Secure POP3 Client
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Store;
public class MainClass {
public static void main(String[] args) throws Exception {
Properties props = new Properties();
String host = "yourserver.edu";
String provider = "pop3";
Session session = Session.getDefaultInstance(props, new MailAuthenticator());
Store store = session.getStore(provider);
store.connect(host, null, null);
Folder inbox = store.getFolder("INBOX");
if (inbox == null) {
System.out.println("No INBOX");
System.exit(1);
}
inbox.open(Folder.READ_ONLY);
Message[] messages = inbox.getMessages();
for (int i = 0; i < messages.length; i++) {
System.out.println("Message " + (i + 1));
messages[i].writeTo(System.out);
}
inbox.close(false);
store.close();
}
}
class MailAuthenticator extends Authenticator {
public MailAuthenticator() {
}
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("username", "password");
}
}
Send E-Mail
import java.io.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
public class SendApp {
public static void send(String smtpHost, int smtpPort, String from, String to, String subject,
String content) throws AddressException, MessagingException {
java.util.Properties props = new java.util.Properties();
props.put("mail.smtp.host", smtpHost);
props.put("mail.smtp.port", "" + smtpPort);
Session session = Session.getDefaultInstance(props, null);
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(from));
msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
msg.setSubject(subject);
msg.setText(content);
Transport.send(msg);
}
public static void main(String[] args) throws Exception {
send("hostname", 25, "j@s.ru", "s@s.ru", "re: dinner", "body");
}
}