0
現在只需進行測試,但您是否可以發送和接收來自同一班級的郵件?收發同班同學的郵件嗎?
package com.mailserver;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.internet.MimeMessage;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
@SuppressWarnings("serial")
public class MailHandlerServlet extends HttpServlet {
public static final Logger _log = Logger.getLogger(MailHandlerServlet.class.getName());
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
sendmail();
try {
Properties props = new Properties();
Session session = Session.getDefaultInstance(props, null);
MimeMessage message = new MimeMessage(session, req.getInputStream());
//Extract out the important fields from the Mime Message
String subject = message.getSubject();
_log.info("Got an email. Subject = " + subject);
String contentType = message.getContentType();
_log.info("Email Content Type : " + contentType);
printParts(message);
//Parse out the Multiparts
//Perform business logic based on the email
}
catch (Exception ex) {
_log.log(Level.WARNING, "Failure in receiving email : " + ex.getMessage());
}
}
private static void printParts(Part p) throws IOException, MessagingException {
Object o = p.getContent();
if (o instanceof String) {
System.out.println("This is a String");
System.out.println((String)o);
}
else if (o instanceof Multipart) {
System.out.println("This is a Multipart");
Multipart mp = (Multipart)o;
int count = mp.getCount();
for (int i = 0; i < count; i++) {
printParts(mp.getBodyPart(i));
}
}
else if (o instanceof InputStream) {
System.out.println("This is just an input stream");
InputStream is = (InputStream)o;
int c;
while ((c = is.read()) != -1)
System.out.write(c);
}
}
private static void sendmail() {
_log.info("Email Sent");
Properties props2 = new Properties();
Session session2 = Session.getDefaultInstance(props2, null);
String msgBody = "...";
try {
Message msg = new MimeMessage(session2);
msg.setFrom(new InternetAddress("[email protected]", "Example.com Admin"));
msg.addRecipient(Message.RecipientType.TO,
new InternetAddress("[email protected]", "Mr. User"));
msg.setSubject("Your Example.com account has been activated");
msg.setText(msgBody);
Transport.send(msg);
} catch (AddressException e) {
// ...
} catch (MessagingException e) {
// ...
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
不用說,它不是給我擁有我的郵件,如果它的,因爲那裏有一些衝突的疑惑?
TIA