Jenkins Pipeline script -> Send email - email

I have a Jenkins Pipeline project and want to send out an email.
I did set up the SMTP settings for Jenkins (Manage Jenkins -> Configure System -> E-mail Notification) and could successfully send a test mail by using the "Test Settings" button.
But if I use my Pipepline project with the following pipeline script:
post {
always {
emailext body: 'A Test EMail!3', recipientProviders: [[$class: 'DevelopersRecipientProvider'], [$class: 'RequesterRecipientProvider']], subject: 'Test 999'
}
}
It fails with the following error:
Connection error sending email, retrying once more in 10 seconds...
Is there another place where I have to configure SMTP settings?

You need to configure email notification in the Configure Jenkins page

Related

Jenkins send e-mail notification to github committers

We want to send out e-mail notifications to our contributors if the Jenkins build was successful or not.
we are using the email extension plugin: https://plugins.jenkins.io/email-ext/
Notifications should be sent in the following cases:
The current build failed or is unstable
the current build is successful and the previous build failed or was unstable
I created a shared library with the following script
#!/usr/bin/env groovy
def call(String buildStatus = 'STARTED') {
buildStatus = buildStatus ?: 'SUCCESS'
def subject = "JENKINS NOTIFICATION - ${buildStatus}: Job '${env.JOB_NAME} [${env.BUILD_NUMBER}]'"
def details = """${buildStatus}: Job '${env.JOB_NAME} [${env.BUILD_NUMBER}]'"""
// Send email to user who has started the build
emailext(
subject: subject,
body: details,
attachLog: true,
compressLog: true,
recipientProviders: [[$class: 'RequesterRecipientProvider'], [$class: 'CulpritsRecipientProvider']]
)
}
In the Jenkinsfile I loaded the library shared-lib and I defined the sendNotification command in the post-block of the jenkinsfile:
#!groovy
#Library('shared-lib') _
pipeline {
agent any
stages{
stage('Checkout code base'){
steps{
checkout scm
}
}
stage('another stage'){
steps{
echo "do something"
}
}
}
post{
always{
sendNotifications currentBuild.result
}
}
}
Currently, the e-mail notifications are sent when I manually trigger a build at Jenkins, but when I push to GitHub and Jenkins build gets triggered, no e-mail notification is sent.
This is the log of the pipeline:
19:12:06 [Pipeline] emailext
19:12:06 Sending mail from default account using System Admin e-mail address
19:12:06 messageContentType = text/plain; charset=UTF-8
19:12:06 Request made to attach build log
19:12:06 Request made to compress build log
19:12:06 Adding recipients from project recipient list
19:12:06 Not sending mail to user noreply-github+ms#companyname.com with no permission to view NewSimple » MTEvent » master #203 Collecting change authors...
19:12:06 build: 203
19:12:06 adding author: noreply-github+ms
19:12:06 Not sending mail to user noreply-github+ms#companyname.com with no permission to view NewSimple » MTEvent » master #203Adding recipients from trigger recipient list
19:12:06 Successfully created MimeMessage
19:12:06 An attempt to send an e-mail to empty list of recipients, ignored.
PS: I don't know from where this email noreply-github+ms#companyname.com was pickup.
The correct email address should be myfirstname.lastname#companyname.com
Not sure what I have missed.
Any suggestions would be appreciated.

Sending a Mail on Jenkins Pipeline

hi I have a simple pipeline job that should send a mail, I configured on Manage jenkins -> Configure System with port 465 and the appropriated SMTP server , when I test the configuration by sending a e-mail , it sends and I can see the test mail on my inbox , but from the pipeline job , it fails:
node {
stage("test") {
def message = "hello there!"
mail bcc: '', body: message, cc: '', from: 'jenkinsuser#mycom.com', replyTo: 'jenkinsuser#mycom.com', subject: "Develop: build generated ", to:'grace#mycom.com'
}
}
Error:
java.net.SocketException: Connection closed by remote host
at sun.security.ssl.SSLSocketImpl.checkWrite(Unknown Source)
at sun.security.ssl.AppOutputStream.write(Unknown Source)
at com.sun.mail.util.TraceOutputStream.write(TraceOutputStream.java:114)
at java.io.BufferedOutputStream.flushBuffer(Unknown Source)
at java.io.BufferedOutputStream.flush(Unknown Source)
at com.sun.mail.smtp.SMTPTransport.sendCommand(SMTPTransport.java:2104)
Caused: javax.mail.MessagingException: Can't send command to SMTP host;
nested exception is:
java.net.SocketException: Connection closed by remote host
at com.sun.mail.smtp.SMTPTransport.sendCommand(SMTPTransport.java:2106)
at com.sun.mail.smtp.SMTPTransport.sendCommand(SMTPTransport.java:2093)
at com.sun.mail.smtp.SMTPTransport.close(SMTPTransport.java:1184)
Any suggestion how to fix it?
thanks,
I am using Email Extension plugin in scripted pipeline with no issues. Make sure you properly configured E-mail Notification section in Manage Jenkins > Configure System. Example for gmail:
Jenkins e-mail notifications settings
Plugin usage is described here: here. This is how I call it in Pipeline (I didn't remove variables):
emailext attachmentsPattern: "**/packages/rpm/splitted/${file}",
to: "${to}",
from: "Jenkins",
subject: "[jenkins] ${packageFullName}: part ${part}/${files.size()}",
body: "File received: \'${file}\'\n" +
"From package: \'${packageFullName}\'\n" +
"Package MD5: \'${mainMdFiveSum}\'\n" +
"Jenkins Build: \'${env.BUILD_URL}\'\n"

Client does not have permissions to send as this sender in Jenkins

I installed Jenkins (Jenkins ver. 2.46.2) and i have configured SMTP Server in Manage Jenkins -> Configure System -> Email Notification.
Test mail is works fine. But in Job email notification not working.
Error message as : Error sending to the following VALID addresses
I checked the Jenkins log file.
550 5.7.60 SMTP; Client does not have permissions to send as this sender [KL1PR03MB1749.apcprd03.prod.outlook.com]
DEBUG SMTP: got response code 550, with response: 550 5.7.60 SMTP; Client does not have permissions to send as this sender [KL1PR03MB1749.apcprd03.prod.outlook.com]
RSET
250 2.0.0 Resetting
com.sun.mail.smtp.SMTPSendFailedException: 550 5.7.60 SMTP; Client does not have permissions to send as this sender [KL1PR03MB1749.apcprd03.prod.outlook.com]
at com.sun.mail.smtp.SMTPTransport.issueSendCommand(SMTPTransport.java:2057)
at com.sun.mail.smtp.SMTPTransport.finishData(SMTPTransport.java:1862)
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1100)
at javax.mail.Transport.send0(Transport.java:195)
at javax.mail.Transport.send(Transport.java:124)
at hudson.plugins.emailext.ExtendedEmailPublisher.sendMail(ExtendedEmailPublisher.java:357)
at hudson.plugins.emailext.ExtendedEmailPublisher._perform(ExtendedEmailPublisher.java:322)
at hudson.plugins.emailext.ExtendedEmailPublisher.perform(ExtendedEmailPublisher.java:230)
at hudson.tasks.BuildStepMonitor$1.perform(BuildStepMonitor.java:20)
at hudson.model.AbstractBuild$AbstractBuildExecution.perform(AbstractBuild.java:779)
at hudson.model.AbstractBuild$AbstractBuildExecution.performAllBuildSteps(AbstractBuild.java:720)
at hudson.model.Build$BuildExecution.cleanUp(Build.java:196)
at hudson.model.Run.execute(Run.java:1775)
at hudson.model.FreeStyleBuild.run(FreeStyleBuild.java:43)
at hudson.model.ResourceController.execute(ResourceController.java:98)
at hudson.model.Executor.run(Executor.java:405)
QUIT
How to fix this issue?
You need to set "System Admin email address" under Manage Jenkins -> Configure System. This is under the Jenkins Location header on that page!
Have a look at below thread.
How can I set the Sender's address in Jenkins?

Getting "Client was not authenticated to send anonymous mail during MAIL FROM" error from Exchange SMTP using Rust lettre library

I am writing a Rust application that will send email through an Exchange server with SMTP functionality enabled. According to Microsoft's webpage, the settings that are required are:
Server address smtp.office365.com
Port 587
StartTLS Enabled
Credentials for mail account login
These are corroborated by the POP/IMAP settings of the webmail service.
Here is my code (with some censoring):
extern crate lettre;
use self::lettre::email::EmailBuilder;
use self::lettre::transport::smtp::{SecurityLevel, SmtpTransportBuilder, SUBMISSION_PORT};
use self::lettre::transport::smtp::authentication::Mechanism;
use self::lettre::transport::EmailTransport;
pub fn send_mail() {
let email = EmailBuilder::new()
.from("my email")
.to("destination email")
.body("testing")
.subject("testing")
.build()
.unwrap();
// Connect to SMTP server
let mut transport = SmtpTransportBuilder::new(("smtp.office365.com", SUBMISSION_PORT))
.expect("Failed to create email transport")
.encrypt()
.smtp_utf8(true)
.credentials("my email", "my password")
.authentication_mechanism(Mechanism::Login)
.build();
println!("Mail transport built");
println!("{:?}", transport.send(email.clone()));
}
When I compile and run the code,it gives me this error:
Err(Permanent(Response { code: Code { severity:
PermanentNegativeCompletion, category: Unspecified3, detail: 0 },
message: ["5.7.57 SMTP; Client was not authenticated to send anonymous
mail during MAIL FROM [SYXPR01CA0106.ausprd01.prod.outlook.com]"] }))
Why is this happening?
The closest I've come in my research is an issue on GitHub in relation to the lettre library not supporting the Login authentication mechanism (which Office 365 uses); however, the codebase was updated to support Login and I am using the master branch directly from GitHub so theoretically my application should support the Login mechanism.
Edit: Forgot to mention that I attempted an EHLO to the server, but it returned a (Client:(Connection closed)) error.
I used telnet and openssl to try connecting directly to my SMTP server, where I found that AUTH LOGIN requires 3 commands; one to send the AUTH LOGIN code, one to send the username and another to send the password. I found that the lettre library implements all its AUTH commands as single commands, so this wasn't working with the server. I downloaded the source code for the library, changed the send function to do the three separate commands, recompiled my code and everything worked fine :)
My addition to the lettre code:
if (accepted_mechanisms[0] == Mechanism::Login) &&
(accepted_mechanisms.capacity() == 1) {
try_smtp!(self.client.command("AUTH LOGIN"), self);
try_smtp!(self.client.command(base64::encode_config(
&username.as_bytes(),
base64::STANDARD).as_str()), self);
try_smtp!(self.client.command(base64::encode_config(
&password.as_bytes(),
base64::STANDARD).as_str()), self);

How to send email with Jenkins and an parameter address?

I'm using Jenkins and I would like to send an email after finished job. The problem I have is that I want to use the username defined before into a parameter in the configuration. I try to use then ${username} but i doesn't work. This is the error I get:
Sending e-mails to: ${username}#email.es
ERROR: Invalid Addresses
javax.mail.SendFailedException: Invalid Addresses;
nested exception is:
com.sun.mail.smtp.SMTPAddressFailedException: 550 5.1.1 <${username}#email.es>... User unknown
at com.sun.mail.smtp.SMTPTransport.rcptTo(SMTPTransport.java:1835)
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1098)
at javax.mail.Transport.send0(Transport.java:195)
at javax.mail.Transport.send(Transport.java:124)
at hudson.tasks.MailSender.run(MailSender.java:126)
at hudson.tasks.MailSender.execute(MailSender.java:101)
at hudson.maven.MavenModuleSetBuild$MavenModuleSetBuildExecution.cleanUp(MavenModuleSetBuild.java:1064)
at hudson.model.Run.execute(Run.java:1764)
at hudson.maven.MavenModuleSetBuild.run(MavenModuleSetBuild.java:531)
at hudson.model.ResourceController.execute(ResourceController.java:89)
at hudson.model.Executor.run(Executor.java:240)
Caused by: com.sun.mail.smtp.SMTPAddressFailedException: 550 5.1.1 <${username}#email.es>... User unknown
at com.sun.mail.smtp.SMTPTransport.rcptTo(SMTPTransport.java:1686)
... 10 more
It is not taking the value of the parameter. Is thera any plugin or way to do this ?
Thanks for your help.
instead of ${username} - use $username
Ex: $username#$domain.com
Here, username and domain are two parameters for build
(defined by selecting checkbox-This build is parameterized)
Configure Jenkins System for Email Notifications
To do this:
"Jenkins Dashboard -> Manage Jenkins -> Configure System"
At the bottom of the page- find : Email Notification
Then give email notification details
I have configured like this:
SMTP server : smtp.gmail.com
Default user e-mail suffix : #gmail.com
select checkbox USE smtp authentication
give: username (without #gmail.com) -eg: enter mike for mike#gmail.com
give your password
Select checkbox Use SSL
SMTP port : 465
try your email settings by sending a test mail
If your able to send it successfuly. its done
/* In the Build - The Build is Parameterized */
1st parameter
Name : username
Default Value : mike
2nd Parameter
Name: domain
Default Value: gmail
//Post-Build Actions - Email Notification
(able to see this only when you have Mailer plugin installed)
Recipients : $username#$domain.com
This should work ..
I 'found' the solution. With a maven project, it doesn' work with the simply Email notification inside the Build properties. I must use a plugin 'Ext-mail plugin' to do it. Thanks for all.