Last active
October 20, 2021 10:40
-
-
Save SoltauFintel/143ce6877a8450d26c575f5480b29e7c to your computer and use it in GitHub Desktop.
SMTP Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*Gradle: | |
implementation 'com.github.bbottema:simple-java-mail:5.0.1' | |
aktuellste Version ist mittlerweile: group: 'org.simplejavamail', name: 'simple-java-mail', version: '6.6.1' | |
Webseite: https://www.simplejavamail.org/features.html */ | |
import java.time.LocalDateTime; | |
import org.pmw.tinylog.Logger; | |
import org.simplejavamail.email.EmailBuilder; | |
import org.simplejavamail.mailer.Mailer; | |
import org.simplejavamail.mailer.MailerBuilder; | |
public class MailSender { | |
private final Mailer mailer; | |
public String fromName; | |
protected String fromMailAddress; | |
protected String forceTo; | |
/** Test */ | |
public static void main(String[] args) { | |
// c is Config object | |
System.out.println("send mail to " + c.get("mail.test.to") + " using SMTP server " + c.get("mail.smtp-server")); | |
new MailSender().sendMail(c.get("mail.test.to"), | |
"Testmail", | |
"Dies ist ein Test.\n Umlaute: äöüÄÖÜß.\n\n" + LocalDateTime.now().toString() + "\nhttp://google.de\nend"); | |
System.out.println("done"); | |
} | |
/** | |
* Initialize mailer using the app config file. | |
*/ | |
public MailSender() { | |
// c is Config object | |
Integer port = 25; | |
mailer = MailerBuilder | |
.withSMTPServer(c.get("mail.smtp-server"), port) | |
.withSMTPServerUsername(c.get("mail.username")) | |
.withSMTPServerPassword(c.get("mail.password")) | |
.buildMailer(); | |
fromName = c.get("mail.from.name"); | |
fromMailAddress = c.get("mail.from.mail-address"); | |
forceTo = c.get("mail.to", ""); | |
} | |
/** | |
* Sends mail! | |
* | |
* @param to recipient mail address | |
* @param subject | |
* @param plainText can contain links starting with http:// | |
*/ | |
public void sendMail(String to, String subject, String plainText) { | |
String sendTo = forceTo.isEmpty() ? to : forceTo; | |
mailer.sendMail(EmailBuilder.startingBlank() | |
.from(fromName, fromMailAddress) | |
.to(sendTo) | |
.withSubject(subject) | |
.withPlainText(plainText) | |
.buildEmail()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment