Skip to content

Instantly share code, notes, and snippets.

@sebcreme
Created August 31, 2010 17:36
Show Gist options
  • Save sebcreme/559405 to your computer and use it in GitHub Desktop.
Save sebcreme/559405 to your computer and use it in GitHub Desktop.
import java.util.*;
import java.io.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
public class Mailer {
public static void main(String[] args) throws IOException {
String to = "sebastien.creme@gmail.com";
String from = "toto@toto.com";
String msgText1 = "Sending a file.\n";
String subject = "Sending a file";
// create some properties and get the default Session
Properties props = System.getProperties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.starttls.enable","true");
props.put("mail.smtp.auth", "true");
//FIRST PROBLEM :: Authentification
class SMTPAuthenticator extends javax.mail.Authenticator {
public PasswordAuthentication getPasswordAuthentication() {
String username = "scr@zenexity.fr";
String password = "demotest";
return new PasswordAuthentication(username, password);
}
}
Authenticator auth = new SMTPAuthenticator();
Session session = Session.getInstance(props, auth);
try {
// create a message
MimeMessage msg = new MimeMessage(session);
//msg.setFrom(new InternetAddress(from));
InternetAddress[] address = {new InternetAddress(to)};
msg.setRecipients(Message.RecipientType.TO, address);
msg.setSubject(subject);
// create and fill the first message part
MimeBodyPart mbp1 = new MimeBodyPart();
mbp1.setText(msgText1);
//SECOND :: send file
// create the second message part
MimeBodyPart mbp2 = new MimeBodyPart();
File file = new File("test.txt");
System.out.println("exists : "+file.exists());
// attach the file to the message
mbp2.attachFile("test.txt");
FileDataSource fds = new FileDataSource(new File("test.txt")) {
public String getContentType() {
return "application/octet-stream";
}
};
mbp2.setDataHandler(new DataHandler(fds));
mbp2.setFileName(fds.getName());
// create the Multipart and add its parts to it
Multipart mp = new MimeMultipart();
mp.addBodyPart(mbp1);
mp.addBodyPart(mbp2);
mp.addBodyPart(mbp1);
// add the Multipart to the message
msg.setContent(mp);
// set the Date: header
msg.setSentDate(new Date());
msg.saveChanges();
mbp2.setHeader("Content-Transfer-Encoding", "base64");
// send the message
Transport.send(msg);
} catch (MessagingException mex) {
mex.printStackTrace();
Exception ex = null;
if ((ex = mex.getNextException()) != null) {
ex.printStackTrace();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment