1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
| import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
public class SendMail {
String d_email = "*******", //unkenntlich gemachte Versendermail
d_password = "********!", //unkenntlich gemachtes PW
d_host = "*******", //unkenntlich gemachter Server
d_port = "25",
m_subject = "Testing",
m_text = "Hey, this is the testing email.";
public SendMail(String to, String fileAttachment) throws Exception {
Properties props = new Properties();
props.put("mail.smtp.user", d_email);
props.put("mail.smtp.host", d_host);
props.put("mail.smtp.port", d_port);
props.put("mail.smtp.starttls.enable","true");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.socketFactory.port", d_port);
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
try {
Authenticator auth = new SMTPAuthenticator();
Session session = Session.getInstance(props, auth);
// Define message
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(d_email));
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
msg.setSubject(m_subject);
// create the message part
MimeBodyPart messageBodyPart = new MimeBodyPart();
//fill message
messageBodyPart.setText(m_text);
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
// Part two is attachment
messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(fileAttachment);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(fileAttachment);
multipart.addBodyPart(messageBodyPart);
// Put parts in message
msg.setContent(multipart);
// Send the message
Transport.send(msg);
} catch (Exception mex) {
mex.printStackTrace();
}
}
private class SMTPAuthenticator extends javax.mail.Authenticator {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(d_email, d_password);
}
}
public static void main(String[] args) {
String to = "*********"; //unkenntlich gemachte Empfängermail
String fileAttachment = "C:/path/to/my/attachment/myPDF.pdf";
try {
new SendMail(to, fileAttachment);
} catch (Exception e) {
e.printStackTrace();
}
}
} |
Lesezeichen