Skip to content

Instantly share code, notes, and snippets.

@quchie
Last active November 27, 2022 23:19
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save quchie/3e02c5d5df8de804e8e0 to your computer and use it in GitHub Desktop.
Save quchie/3e02c5d5df8de804e8e0 to your computer and use it in GitHub Desktop.
Send email using groovy script
import javax.mail.*
import javax.mail.internet.*
/*
Get Any JAVAMAIL Dependency
===============================
Download JAVAMAIL dependency that you need.
download JAVAMAIL at : https://maven.java.net/content/repositories/releases/com/sun/mail/javax.mail/1.5.2/javax.mail-1.5.2.jar
To install, copy & paste the *.jar to installed Groovy lib directory:
eg: C:\Program Files (x86)\Groovy\Groovy-2.1.1\lib
*/
public class SMTPAuthenticator extends Authenticator
{
public PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication('email@gmail.com', 'password111');
}
}
def d_email = "email@gmail.com",
d_uname = "email@gmail.com",
d_password = "password111",
d_host = "smtp.gmail.com",
d_port = "465", //465,587
m_to = "email@astrums.net",
m_subject = "Testing",
m_text = "Hey, this is the testing email."
def 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.debug", "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")
def auth = new SMTPAuthenticator()
def session = Session.getInstance(props, auth)
session.setDebug(true);
def msg = new MimeMessage(session)
msg.setText(m_text)
msg.setSubject(m_subject)
msg.setFrom(new InternetAddress(d_email))
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(m_to))
Transport transport = session.getTransport("smtps");
transport.connect(d_host, d_port, d_uname, d_password);
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();
@urbansky
Copy link

Thank you for the script.
Please look at line 56. There is the fixed port number 465, but you have configuration variables.

@quchie
Copy link
Author

quchie commented Aug 11, 2016

Thank you. Great to know it helps you.
I have fixed it, but i think this is very dirty script to begin with :) lets see if i can make it better later.

@pb60704
Copy link

pb60704 commented Sep 1, 2016

I'm not able to reuse the code in my IntelliJ IDE, javax.mail is not recognised and shows compile error.Please help.

@Mugi4ok
Copy link

Mugi4ok commented Sep 29, 2016

@pb60704, have you read this?


Get Any JAVAMAIL Dependency 
===============================
Download JAVAMAIL dependency that you need.
download JAVAMAIL at : https://maven.java.net/content/repositories/releases/com/sun/mail/javax.mail/1.5.2/javax.mail-1.5.2.jar
To install, copy & paste the *.jar to installed Groovy lib directory:
eg: C:\Program Files (x86)\Groovy\Groovy-2.1.1\lib

*/

@mdeimel
Copy link

mdeimel commented Dec 13, 2017

Thanks for this script, it provided some helpful information. I tried to whittle it down to the bare minimum of what was required (at least for my use case). And here it is, hopefully it can be helpful.

@Grab(group = 'com.sun.mail', module = 'javax.mail', version = '1.6.0')

import javax.mail.Message
import javax.mail.Session
import javax.mail.Transport
import javax.mail.internet.InternetAddress
import javax.mail.internet.MimeMessage

MAILER_HOST = "mailtrap.io"
MAILER_USER = "<user account>"
MAILER_PASS = "<password>"
MAILER_PORT = 2525

private void runScript() {
    Session session = Session.getDefaultInstance(new Properties())

    MimeMessage message = new MimeMessage(session)
    message.setFrom("no.reply@example.org")
    message.setRecipient(Message.RecipientType.TO, new InternetAddress("email@example.org"))
    message.setSubject("Important message!")
    message.setText("Here is an important email message!")

    Transport transport = session.getTransport("smtp")
    transport.connect(MAILER_HOST, MAILER_PORT, MAILER_USER, MAILER_PASS)
    transport.sendMessage(message, message.getAllRecipients())
    transport.close()
}

runScript()

@markhu
Copy link

markhu commented Apr 17, 2018

Thanks, guys! Here's a slightly shorter version that doesn't require SMTP AUTH... (probably only works if recipient domain is served by MAILER_HOST.

#!/usr/bin/env groovy

@Grab(group = 'com.sun.mail', module = 'javax.mail', version = '1.6.0')

import javax.mail.*
import javax.mail.internet.*

MAILER_HOST = "aspmx.l.google.com"  // "smtp-relay.gmail.com"
RECIPIENT_EMAIL = "my+test@example.com"
date_time = new Date().format("yyyy-MM-dd hh:mm")
props = new Properties()

private void runScript() {
    props.put("mail.host", MAILER_HOST);
    Session session = Session.getDefaultInstance(props)
    session.setDebug(true);

    MimeMessage message = new MimeMessage(session)
    message.setFrom("no.reply@example.org")
    message.setRecipient(Message.RecipientType.TO, new InternetAddress(RECIPIENT_EMAIL))
    message.setSubject("A Test email ${date_time}")
    message.setText("This is a sample email message!")

    Transport.send(message)
}

runScript()

@kaushalsingh861
Copy link

Works perfectly, Thank you very much!!!

@QAmer91
Copy link

QAmer91 commented Sep 10, 2019

I Faced an error while trying the above code which is
groovy.lang.MissingMethodException: No signature of method:
com.sun.mail.smtp.SMTPSSLTransport.connect()is applicable for argument types: (java.lang.String, java.lang.String, java.lang.String, java.lang.String) values: [smtp.gmail.com, 465, email@gmail.com, password111] Possible solutions: connect(), connect(java.lang.String, java.lang.String, java.lang.String), connect(java.lang.String, int, java.lang.String, java.lang.String),connect(java.lang.String, java.lang.String), collect(), connect(java.net.Socket)
I fixed it by modifying parameters in transport.connect(d_host, d_port, d_uname, d_password); to transport.connect(d_host, d_port.toInteger(), d_uname, d_password);

@ocomsoft
Copy link

Changing Line 29 to
d_port = 465, //465,587

Works better for me.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment