Ok. Here's the code. I took it right from http://www.shiffman.net. And just replaced the message with a multipart message.
Three files.
save_attachment.pde
Code:
// Daniel Shiffman
// http://www.shiffman.net
// Simple E-mail Checking
// This code requires the Java mail library
// smtp.jar, pop3.jar, mailapi.jar, imap.jar, activation.jar
// Download:// http://java.sun.com/products/javamail/
import javax.mail.*;
import javax.mail.internet.*;
void setup() {
size(200,200);
sendMail();
println("Finished");
noLoop();
}
Auth.pde
Code:
// Daniel Shiffman
// http://www.shiffman.net
// Simple Authenticator
// Careful, this is terribly unsecure!!
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
public class Auth extends Authenticator {
public Auth() {
super();
}
public PasswordAuthentication getPasswordAuthentication() {
String username, password;
username = "username@gmail.com";
password = "password";
System.out.println("authenticating. . ");
return new PasswordAuthentication(username, password);
}
}
MailStuff
Code:
// Daniel Shiffman
// http://www.shiffman.net
// Example functions that send mail (smtp)
// You can also do imap, but that's not included here
// A function to check a mail account
// A function to send mail
void sendMail() {
// Create a session
String host="smtp.gmail.com";
Properties props=new Properties();
// SMTP Session
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
// We need TTLS, which gmail requires
props.put("mail.smtp.starttls.enable","true");
// Create a session
Session session = Session.getDefaultInstance(props, new Auth());
try
{
MimeMessage msg=new MimeMessage(session);
msg.setFrom(new InternetAddress("username@gmail.com", "Name"));
msg.addRecipient(Message.RecipientType.TO,new InternetAddress("recipient@address.com"));
msg.setSubject("Email with Processing");
BodyPart messageBodyPart = new MimeBodyPart();
// Fill the message
messageBodyPart.setText("Email sent with Processing");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
// Part two is attachment
messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource("c:\\image.jpg");
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName("image.jpg");
multipart.addBodyPart(messageBodyPart);
msg.setContent(multipart);
msg.setSentDate(new Date());
Transport.send(msg);
println("Mail sent!");
}
catch(Exception e)
{
e.printStackTrace();
}
}
I haven't found a way to send the file with a relative path, without the "c:\" (by the way, you need double \ so you escape one of them).
I don't have the part where I save the file, but it's not hard just to save it to "c:\image.jpg" and send that one.
I used my gmail account with that port and everything went well, although I don't know if the account/password are sent in the clear or encrypted, so you might wanna check first.